Can I use STDIN for IPC?

1.1k Views Asked by At

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;
}
1

There are 1 best solutions below

2
On BEST ANSWER

You can use pipe for IPC. Now if you want to use STDIN_FILENO and STDOUT_FILENO it would look like this:

#include <unistd.h>
#include <stdio.h>

int main(void) {
    char val = '!';
    int filedes[2];
    pipe(filedes);
    int proc = fork();
    if (proc < 0)
        return -1;
    if (proc == 0) {
        close(1);
        dup(filedes[1]);
        close(filedes[0]);
        close(filedes[1]);
        write(1, &val, 1);
        return 0;
    }
    else {
        char ch[2] = { 0 };
        close(0);
        dup(filedes[0]);
        close(filedes[0]);
        close(filedes[1]);
        read(0, ch, 1);
        printf("%s\n", ch);
        return 0;
    }
    return -2;
}

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.