Question

I want to implement communication between child process and it's parent using pipe. Here is the code:

#include <stdio.h>
int main() {
    int pipe_dsc[2];
    if (pipe(pipe_dsc) == -1) {
        printf("error\n");
    }
    switch (fork()) {
        case -1:
            printf("error\n");
            return 0;
        case 0: //children
            close(0);
            dup(pipe_dsc[0]);

            close(pipe_dsc[1]);

            int x;
            scanf("%d", &x);

            printf("succes: %d\n", x);
            return 0;

        default: //parent
            close(1);
            dup(pipe_dsc[1]);

            close(pipe_dsc[0]);
            printf("127");

            wait(0);
            return 0;
    }
    return 0;
}

Parent should write an number 127 and child should read it, but it doesn't. Child keeps waiting at scanf. What is wrong?

Was it helpful?

Solution

I guess that flushing could help:

fflush(stdout);

But in my test I achieved success by adding a \n to the string. That sscanf won't start with "unfinished" strings I guess.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top