[英]Multiple pipes and processes
I am trying to communicate with children processes and make them sort a part of a list. 我正在尝试与子进程进行通信,并使它们成为列表的一部分。 My problem is children processes read everything but do nothing after it.
我的问题是儿童过程阅读所有内容,但在此之后什么都不做
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;
I tried to see if children process wait in the while(read) loop, but when i close the write end of pipes from the parent process they should leave the loop. 我试图看看子进程是否在while(read)循环中进行等待,但是当我从父进程关闭管道的写入结束时,它们应该离开循环。
You're probably thinking that some specific pipe[2]
is shared by the parent and it's respective child process. 您可能认为某个特定的
pipe[2]
由父级共享,并且它是相应的子进程。 That's true ... However it is also shared by all the other children processes you create along the way - and because it's opened, those other children processes also inherit it as opened. 这是真的......但是,它也会在您创建的所有其他子进程中共享 - 并且因为它已打开,其他子进程也会将其继承为已打开。
Doing this at the beginning of your child pid check worked for me: 在您的孩子pid检查开始时这样做对我有用:
if (pid == 0) {
int j;
for (j = 0; j < num_children; j++) {
if (j != i) {
close(fd[j][0]);
close(fd[j][1]);
}
}
...
}
I suspect that the reading from the pipe via: 我怀疑通过管道读取:
while ( read(fd[i][0], &received, sizeof(int)) > 0) while(读取(fd [i] [0],&received,sizeof(int))> 0)
is being blocked/haulted until data is available on the pipe. 被阻止/被阻止,直到管道上有数据可用。 If so, this would explain the lack of response from your code after this point.
如果是这样,这将解释在此之后您的代码缺乏响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.