简体   繁体   中英

Writing to a pipe is not working after many fork

I have following testing program, I which I like to send(write) the data from deepest-child to the parent.

Code is:

#define M1 "Message One"
int main(int argc, char **argv) {
int f1[2];
char buff[32];

pipe(f1);

if (fork() == 0) {
    if (fork() == 0) {
        if (fork() == 0) {
            printf("%s :%d\n", "f1[0] :",f1[0]);
            while(read(f1[0], buff, sizeof(buff)) > 0)
                 printf("%s\n", buff);
                     return 0;
         } else {
            //do nothing
        }
    } else {
        //do nothing
    }

} else {    
    sleep(2);
    printf("%s :%d\n", "f1[1] :",f1[1]);
    if(write(f1[1], M1, sizeof(M1) < 0))
    printf("%s\n","Error");
    return 0;
}
return 0;
}

The problem with my code is, the program is not printing the message.

I am not sure if this is related with many fork.

Close the unused file descriptors it will work fine

In the inner most child

close(f1[1]);

In the parent process

close(f1[0]);

And also syntax error in the line write is called change it to

write(f1[1], M1, sizeof(M1)) < 0)  

change your if statement to

if (write(f1[1], M1, sizeof(M1)) < 0)

instead of

if(write(f1[1], M1, sizeof(M1) < 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM