Last active
April 23, 2018 14:11
-
-
Save yalue/1e288e328110354db26f221eab2a9f59 to your computer and use it in GitHub Desktop.
Note to self: writing to a child process' stdin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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)); | |
return 1; | |
} | |
} | |
// 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