我想请问一下为什么我运行这个程序没有结果直接退出??

nicoletoosimple 2018-06-27 07:05:09
# include<unistd.h>
# include<signal.h>
# include<stdio.h>

int pid1,pid2;
int main(void)
{
int fd[2];
char OutPipe[100],InPipe[100];
pipe(fd);
while((pid1=fork())= = -1);
if(pid1= =0)
{
lockf(fd[1],1,0);
sprintf(OutPipe,“child 1 process is sending message!”);
write(fd[1],OutPipe,50);
sleep(5);
lockf(fd[1],0,0);
exit(0);
}else{
while((pid2=fork())= = -1);
if(pid2= =0)
{
lockf(fd[1],1,0);
sprintf(OutPipe,“child 2 process is sending message!”);
write(fd[1],OutPipe,50);
sleep(5);
lockf(fd[1],0,0);
exit(0);
}else{
wait(0);
read(fd[0],InPipe,50);
printf(“%s\n”,InPipe);
wait(0);
read(fd[0],InPipe,50);
printf(“%s\n”,InPipe);
exit(0);
}
}
}
...全文
187 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
宁南学者 2018-06-28
  • 打赏
  • 举报
回复
程序在ubuntu机器运行没有问题。wait(0) 的时候是等待子进程退出,这个就已经实现了同步。可能和系统处理管道消息有关,如果子进程退出,
发出的消息会丢失。如果父进程先读取阻塞,然后,子进程写,这样能保证。

主要有两点,第一,父进程先进入阻塞 读, 第二 子进程 写的时候,父进程已经在运行,不要子进程写的时候,父进程还没运行。
jklinux 2018-06-28
  • 打赏
  • 举报
回复

wait(0);
read(fd[0],InPipe,50);
printf(“%s\n”,InPipe);
wait(0);
read(fd[0],InPipe,50);
printf(“%s\n”,InPipe);
exit(0);


父进程应先read ...再wait, 子进程先sleep再写。也就是得让父进程先调用read

18,772

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 专题技术讨论区
社区管理员
  • 专题技术讨论区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧