【发布时间】:2020-05-16 14:54:21
【问题描述】:
我正在尝试通过创建具有 3 个子进程的父进程来编写 C 代码,其中父进程通过管道发送文件的五行,所有 3 个子进程在屏幕上打印接收到的字符串。
我知道关于这个主题有几个问题,但我无法解决我的问题,在那里寻找解决方案。
我的问题是只有第一个孩子接收字符串,打印它们然后程序停止。
代码如下:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#define MAX_CHILDREN 3
int main( void )
{
pid_t pid;
int fd[2];
FILE *f;
int num_process;
for(num_process = 0; num_process < MAX_CHILDREN; num_process++)
{
if(pipe(fd) == -1)
{
perror( "pipe Failed" );
continue;
}
pid = fork();
if(pid < 0)
{
perror("fork failed");
exit(1);
}
if(pid == 0)
{ //child code
char buff[256];
printf("Child %i (pid= %i)\n", num_process, getpid());
close(fd[1]);
while(read( fd[0], buff, sizeof(buff))>0)
{
printf("Read child = %s\n", buff);
}
exit(0);
}
else{//parent
printf("Im parent %i\n",getpid());
close(fd[0]);
int i;
int str_len=256;
char str[str_len];
f=fopen("input.dat","r");
for(i=0;i<5;i++)
{
fgets(str,str_len,f);
write(fd[1], str,strlen(str));
printf("Parent send %s\n", str);
}
wait(NULL);
}
}
fclose(f);
return 0;
}
我得到的输出是这样的:
Im parent 65090
Parent send apple
Parent send banana
Parent send cherry
Parent send cat
Parent send dog
Child 0 (pid= 65091)
Read child = apple
banana
cherry
cat
dog
为什么程序在第一个孩子之后停止?
【问题讨论】:
-
如果将一个字节写入管道,则只能读取一次。在第一个孩子读取数据后,其他孩子就无法读取数据了。如果你想让它被读3次,你需要写3次,然后你就有同步问题要处理。