fork后父子进程通信的例子,有一点值得注意:
fork之后第一时间是子进程在执行,如果子进程不执行sleep(3);,调用read会因为管道无写进程而返回0。因此要等待父进程开始写管道再进行读操作。
- #include <stdio.h>
-
#include <sys/stat.h>
-
#include <unistd.h>
-
#include <fcntl.h>
-
-
int main(void)
-
{
-
pid_t pid;
-
FILE *fp;
-
char buff[100];
-
int i=0;
-
int n;
-
-
unlink("./myfifo");
-
if(mkfifo("./myfifo", 0777) < 0)
-
{
-
printf("error in %s:%d.\n", __FILE__, __LINE__);
-
/* exit(1); */
-
}
-
if((pid = fork()) < 0)
-
{
-
printf("error in %s:%d.\n", __FILE__, __LINE__);
-
exit(1);
-
}
-
if(pid > 0)
-
{
-
fp = open("./myfifo", O_WRONLY);
-
while(1)
-
{
-
i++;
-
memset(buff, 0, 100);
-
sprintf(buff, "------ %d -------\n", i);
-
write(fp, buff, strlen(buff));
-
sleep(3);
-
}
-
}
-
else
-
{
-
fp = open("./myfifo", O_RDONLY);
-
sleep(3);
-
while((n = read(fp, buff, 100) > 0 ))
-
{
-
printf("%s\n", buff);
-
sleep(1);
-
}
-
printf("child process's n%d.\n", n);
-
}
-
return 0;
-
}
阅读(1329) | 评论(0) | 转发(0) |