linux pipe 异步读写,在linux下读写关于PIPE的文章

linux下的一个简单的多进程程序。 输入一些数字,如./findPrime 10 20 30. 该程序将创建3个子进程,以找出2-10,10-20,20-30之间的所有素数。 一旦子进程找到素数,它将通过管道写入“2是素数”并发送给父级。父母会将其打印在屏幕上。 这里的问题是,我使用一个while循环将消息写入管道,并在父级使用另一个while循环来接收消息,但使用下面的代码,它只显示第一条消息,所以我想知道是什么我正在继续,我该如何继续阅读那条管道?我错过了什么?非常感谢!在linux下读写关于PIPE的文章

char readBuffer[100];

char outBuffer[15];

int pids[argc];

int fd[2];

pipe(fd);

for(i = 0; i < argc; i++)

{

if(i == 0)

bottom = 2;

else

bottom = args[i - 1];

top = args[i];

pids[i] = fork();

if(pids[i] == 0)

{

printf("Child %d: bottom=%d, top=%d\n", getpid(), bottom, top);

close(fd[0]);

j = bottom;

while(j <= top)

{

int res = findPrime(j);

if(res == 1)

{

sprintf(outBuffer, "%d is prime", j);

write(fd[1], outBuffer, (strlen(outBuffer)+1));

}

j++;

}

exit(0x47);

}

else if(pids[i] < 0)

{

fprintf(stderr, "fork failed! errno = %i\n", errno);

break;

}

else

{

close(fd[1]);

while((nbytes = read(fd[0], readBuffer, sizeof(readBuffer))) > 0)

printf("%s\n", readBuffer);

int status = 0;

pid = waitpid(pids[i], &status, 0);

if(pid >= 0)

printf("Child %d exited cleanly\n", pid);

}

}

而这些子进程应该在创建它们,就像当过程1完成,然后再处理2将运行,并处理3将后2 我也想父进程显示的顺序运行消息立即收到一个。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值