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 我也想父进程显示的顺序运行消息立即收到一个。