我正试图与孩子们交流过程,并使他们成为列表的一部分。我的问题是,孩子们会阅读所有的东西,但之后什么也不做。
int main(int argc, char *argv[]){
int i;
int num_children;
pid_t pid;
num_children= 3;
int fd[num_children][2]; //PIPES
for (i=0; i<num_children; i++)
{
if (pipe(fd[i]) == -1)
{
printf("couldnt create the pipe\n");
exit(EXIT_FAILURE);
}
}
for (i=0; i<num_children; i++)
{
pid = fork();
if (pid == -1)
{
printf("couldnt create child process %i\n",i);
exit(EXIT_FAILURE);
}
if (pid == 0)
{ //this is child process
close(fd[i][1]); //closing fd[1] the write end of the pipe
int received;
node *list = NULL;
while ( read(fd[i][0], &received, sizeof(int)) > 0)
{
list = insert(list, received);
printf("Process %i got the number: %i\n",i,received); //this part is working perfect
}
printf("Im process %i here is my list: \n",i); //i couldnt get any output from here
printList(list);
close(fd[i][0]);
exit(EXIT_SUCCESS);
}
}
for (i=0; i<num_children; i++) //closing the read end of pipe for parent
{
close(fd[i][0]);
}
int number;
int mod;
FILE *fileIn = fopen ("<file directory>","r");
while(fscanf(fileIn, "%i", &number)>=0)
{
mod = number % num_children;
write(fd[mod][1], &number, sizeof(int));
}
for (int i=0; i<num_children; i++)
{
if(close(fd[i][1])==0)
{
printf("cant close the pipe");
//tried to catch errors, but pipes are closing with no problem i think
}
}
return 0;我试图查看子进程是否在while(read)循环中等待,但是当我从父进程关闭管道的写端时,它们应该离开循环。
发布于 2015-02-25 13:39:53
您可能认为某些特定的pipe[2]是由父进程共享的,并且它是各自的子进程。那是真的..。然而,它也被您沿途创建的所有其他子进程所共享--而且由于它是打开的,这些其他子进程也继承它为opened。
在您的孩子pid检查开始时这样做对我来说是有效的:
if (pid == 0) {
int j;
for (j = 0; j < num_children; j++) {
if (j != i) {
close(fd[j][0]);
close(fd[j][1]);
}
}
...
}发布于 2015-02-25 13:16:51
我怀疑从管道里读出的信息是:
而(改为(外国直接投资,并收到,相当大的(Int))> 0)
正在被阻塞/运输,直到管道上的数据可用为止。如果是这样的话,这将解释为什么您的代码在这一点之后没有响应。
https://stackoverflow.com/questions/28719343
复制相似问题