Can I use standard input for interprocess communication? I wrote the following gnu c code as an experiment, but the program hangs waiting for input after printing the character defined as val
. Neither a newline nor fflush
in the sending process seem to alleviate the problem.
#include <unistd.h>
#include <stdio.h>
int main(void) {
char val = '!';
int proc = fork();
if (proc < 0)
return -1;
if (proc == 0) {
write(0, &val, 1);
return 0;
}
else {
char ch[2] = { 0 };
read(0, ch, 1);
printf("%s\n", ch);
return 0;
}
return -2;
}
You can use pipe for IPC. Now if you want to use STDIN_FILENO and STDOUT_FILENO it would look like this:
Combination close(x) and dup(filedes[x]) closes STDOUT/STDIN makes copy of filedes[x] into first available descriptor, what you just closed. As suggested by Jonathan example is now closing both filedes ends and without any doubts is using STDIN/STDOUT.