hey guys.. I'm trying to create a bunch of children where the parent creates child1, and child1 creates child2 and the parent creates child3 using fork()... and I'm supposed to pass a message through using a pipe, but when I pass from child2 to child3 I have to use a fifo file.. all are working except for the fifo file... so all of them print fine except for child3:
Enter String: kaka
I am parent.
Parent: kaka
I am child1.
Child1: kaka
I am child2.
Child2: kaka
I am child3.
Child3:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
/*#include <sys/wait.h>*/
int main(void)
{
int unnamed[2], nbytes, flag, i;
pid_t pid;
char string[128];
char readbuffer[80];
printf("Enter String: ");
fgets(string, 127, stdin);
mkfifo ("file", S_IXGRP);
i = open("file", O_RDWR|O_NONBLOCK);
pipe(unnamed);
if((pid = fork()) == -1)
{ perror("Fork error.\n");
exit(1);
}
if(pid == 0) /*child1*/
{ printf("I am child1.\n");
nbytes = read(unnamed[0], readbuffer, sizeof(readbuffer));
printf("Child1: %s\n", readbuffer);
write(unnamed[1], readbuffer, (strlen(readbuffer)+1));
if((pid = fork()) == -1)
{ perror("Fork error.\n");
exit(1);
}
if(pid == 0) /*child2*/
{ printf("I am child2.\n");
nbytes = read(unnamed[0], readbuffer, sizeof(readbuffer));
printf("Child2: %s\n", readbuffer);
write(i, readbuffer, (strlen(readbuffer)+1));
}
else
{ wait(&flag);
}
}
else /*parent*/
{ printf("I am parent.\n");
write(unnamed[1], string, (strlen(string)+1));
printf("Parent: %s\n", string);
if((pid = fork()) == -1)
{ perror("Fork error.\n");
exit(1);
}
if(pid == 0) /*child3*/
{ printf("I am child3.\n");
nbytes = read(i, readbuffer, sizeof(readbuffer));
printf("Child3: %s\n", readbuffer);
write(unnamed[1], readbuffer, (strlen(readbuffer)+1));
}
else
{ close(unnamed[0]);
close(unnamed[1]);
}
}
return(0);
}
Why doesn't it print? Thanks in advance.