Skip to content

Instantly share code, notes, and snippets.

@yalue
Created November 12, 2020 20:49
Show Gist options
  • Save yalue/cbc2a246bcc7e71824c45f31cf48cee8 to your computer and use it in GitHub Desktop.
Save yalue/cbc2a246bcc7e71824c45f31cf48cee8 to your computer and use it in GitHub Desktop.
An example of writing to a child process' stdin, in C.
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
// A minimal-ish example of writing data to a child process' stdin.
int main(int argc, char **argv) {
char print_buffer[256];
int stdin_pipe[2];
int result;
pid_t child_pid;
// First, create the pipe.
result = pipe(stdin_pipe);
if (result != 0) {
printf("Failed creating communication pipe: %s\n", strerror(errno));
return 1;
}
// Next, fork.
child_pid = fork();
if (child_pid < 0) {
printf("Fork error: %s\n", strerror(errno));
return 1;
}
if (child_pid == 0) {
// Before exec'ing, the child must set the receiving end of the pipe to
// stdin.
result = dup2(stdin_pipe[0], STDIN_FILENO);
if (result < 0) {
printf("Failed setting pipe to stdin descriptor: %s\n", strerror(errno));
return 1;
}
close(stdin_pipe[1]);
result = execlp("cat", "cat", NULL);
if (result < 0) {
printf("Failed exec'ing a process: %s\n", strerror(errno));
}
}
// Now, the parent can write data to its end of the pipe. The child `cat`
// process should print out this string.
close(stdin_pipe[0]);
memset(print_buffer, 0, sizeof(print_buffer));
snprintf(print_buffer, sizeof(print_buffer), "Hello! %s %f\n", "whatever",
-1337.12);
if (write(stdin_pipe[1], print_buffer, strlen(print_buffer) + 1) <= 0) {
printf("Failed writing to pipe: %s\n", strerror(errno));
return 1;
}
close(stdin_pipe[1]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment