pmverma
pmverma

Reputation: 1703

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.

Upvotes: 1

Views: 232

Answers (2)

sujin
sujin

Reputation: 2853

change your if statement to

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

instead of

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

Upvotes: 1

KARTHIK BHAT
KARTHIK BHAT

Reputation: 1420

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)  

Upvotes: 2

Related Questions