首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多管多工序

多管多工序
EN

Stack Overflow用户
提问于 2015-02-25 12:43:01
回答 2查看 2.3K关注 0票数 4

我正试图与孩子们交流过程,并使他们成为列表的一部分。我的问题是,孩子们会阅读所有的东西,但之后什么也不做。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-25 13:39:53

您可能认为某些特定的pipe[2]是由父进程共享的,并且它是各自的子进程。那是真的..。然而,它也被您沿途创建的所有其他子进程所共享--而且由于它是打开的,这些其他子进程也继承它为opened。

在您的孩子pid检查开始时这样做对我来说是有效的:

代码语言:javascript
复制
if (pid == 0) {
    int j;
    for (j = 0; j < num_children; j++) {
        if (j != i) {
            close(fd[j][0]);
            close(fd[j][1]);
        }
    }
    ...
}
票数 3
EN

Stack Overflow用户

发布于 2015-02-25 13:16:51

我怀疑从管道里读出的信息是:

而(改为(外国直接投资,并收到,相当大的(Int))> 0)

正在被阻塞/运输,直到管道上的数据可用为止。如果是这样的话,这将解释为什么您的代码在这一点之后没有响应。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28719343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档