fork创建进程后子父进程执行顺序
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h> /*包含文件打开模式 S_IRUSR/S_IRGRP/S_IROTH...*/
int main()
{
int fd[2];
if(pipe(fd)==0)
printf("%d %d\n",fd[0],fd[1]);
else
printf("pipe create error!\n");
pid_t childpid;//进程号
printf("default pid_t:%d\n",childpid);
if((childpid=fork())==-1)
{
perror("fork error!\n");
exit(1);
}
printf("pid_t:%d\n",childpid);
char string[]="hello world,the 000 second";
char readbuf[100]={'\0'},writebuf[100]={'\0'};
if(childpid==0)
{//子进程中
close(fd[0]);//关闭管道写端口
//通过管段 向父进程写数据
int i=0;
for(;i<100;i++)
{
sprintf(string,"hello world,the %03d second",i);
write(fd[1],string,strlen(string));
printf("in subprocess:write over!\n\n");
}
}
else
{//父进程中
close(fd[1]);//关闭管道读端口
//通过管道 从子进程中读取数据
int i=0;
for(;i<100;i++)
{
read(fd[0],readbuf,strlen(string));
printf("sunprocess readfrom subprocess:%s\n",readbuf);
}
}
return 0;
}
麻烦 给我讲解一下程序的执行流程。
很疑惑 既然子父进程执行是无序的,又如何确保,每次父进程都能读到子进程新写的数据?(读的数据不重复)
c
[解决办法]
读过的数据就没有啦!
最关键的是子进程每次写的数据都没有超过PIPE_BUF, 否则的话,父进程中不一定每次都能读出完整的数据,
for(;i<100;i++) 不能保证把数据都读出来!
[解决办法]
我只能说这并不能保证. 简单点说,并任何标准,准则保证这个事.
如果程序依赖于这个现象,那这就是一个BUG了.
[解决办法]
你用了pipe管道机制,管道机制本身就是一种同步机制。
[解决办法]
答案同一楼.
一句话,fork出的父子进程并**不保证**任何有规律的执行顺序!
不同linux发行版,不同的系统配置环境,不同的系统负载下很可能结果就不一样了.
所以你的小程序依赖于此种*不保证*的情形是不要靠的!
要解释你的程序出现现象很简单: printf执行时间相对于别的代码执行时间长的多.所以才出现这种现象.
[解决办法]
进程间通讯.