【问题标题】:Multiple pipes and processes多个管道和进程
【发布时间】:2015-04-27 11:10:57
【问题描述】:

我正在尝试与子进程进行通信并使它们成为列表的一部分。我的问题是子进程读取所有内容,但之后什么也不做。

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) 循环中等待,但是当我从父进程关闭管道的写入端时,它们应该离开循环。

【问题讨论】:

  • 你确定这是声明数组的正确方法吗:int fd[num_children][2];
  • 是的,我假设:type arrayName [ x ][ y ];
  • 从来没有使用过可变长度数组。现在阅读标准。

标签: c operating-system pipe fork child-process


【解决方案1】:

您可能认为某些特定的pipe[2] 由父进程共享,并且是各自的子进程。确实如此……但是它也被您在此过程中创建的所有其他子进程共享 - 因为它是打开的,所以其他子进程也会在打开时继承它。

在您的孩子 pid 检查开始时执行此操作对我有用:

if (pid == 0) {
    int j;
    for (j = 0; j < num_children; j++) {
        if (j != i) {
            close(fd[j][0]);
            close(fd[j][1]);
        }
    }
    ...
}

【讨论】:

  • 你是对的,其他管端应该关闭。非常感谢:)
【解决方案2】:

我怀疑是通过管道读取的:

while ( read(fd[i][0], &received, sizeof(int)) > 0)

在管道上可用数据之前被阻塞/拖运。如果是这样,这将解释您的代码在此之后没有响应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多