首页 > 解决方案 > 管道卡在读取中(C - 系统调用)

问题描述

这是我第一次使用 C 语言,所以到目前为止非常困难。我的程序读取一个 file.txt。在第一行中,我必须创建子节点的数量(var: NPROC),在其余行中,我必须读取子节点的进程 ID、两个整数和一个字符,即我必须计算的操作:例如:

NPROC
(id) (n1) (op) (n2)
2
2 3 + 1
1 5 / 2
2 9 * 3

我必须使用消息队列(完美运行)将操作(逐行)发送给孩子,然后孩子应该使用管道发回结果。

这是代码:

(父亲)

//other code
for(i=0; i < NPROC; i++) {

    if(pipe(p) == -1) {
        perror("pipe");
        exit(1);
    }

    switch(currentPid = fork()){
        case 0:

            execl("./child", "./child", NULL);

            return 0;
        case -1:
            printf("Error when forking\n");
            break;
        default:

            // in the father
            childrenPids[i] = currentPid; // store current child pid
            wait(NULL);

            printf("\nParentpid:  %d, Childpid: %i \n", getpid(), currentPid);

            //close(p[1]);

            if(read(p[0], &val, sizeof(val) == -1){
                perror("read()\n");
                exit(1);
            }

            printf("Parent(%d) received value: %d\n", getpid(), val);

            break;         
    }

   //other code


(child)
 //other code
 while (1) {

        long msgtype = m->mtype;
        if(msgrcv(msgid, m, sizeof(message) - sizeof(m->mtype), msgtype, IPC_NOWAIT) == -1) {
            // if(close (p[1]) == -1){
            //     perror("close p[1] of the child\n");
            // } 
            //perror("\nmsgrcv");
            exit(1);
        }
        result[i] = calcolate_results(m);
        // printf("%i %i %c %i", m->id, m->num1, m->op, m->num2);
        printf("\nresult: %i\n", result[i]);

        val = result[i];

        if(write (p[1], &val, sizeof(val)) == -1) { 
            perror("write\n");
            exit(1);
        }
        printf("Child(%d) send val: %d\n", getpid(), val);
    }
 //other code

现在我的问题是父亲的阅读似乎没有得到消息。当我执行程序不退出时,它在父亲的读取处循环(保持不变)。我试图将读取放在 for 之外(因此它至少应该读取最后一条消息)但程序仍然停留在读取中。因此,如果有人可以帮助我,我将非常感激。

标签: cpipesystem-calls

解决方案


您的代码充满了问题。

switch(currentPid = fork()){
    case 0:

在这里,您需要关闭管道的读取端:

        close(p[0]);

通常你会dup2execl这里。通常,如果您的子进程要加载另一个程序,您希望将其 stdout 重定向到管道的写入端,如dup2(p[1], 1); close(p[1]);.

        execl("./child", "./child", NULL);

        return 0;
    case -1:
        printf("Error when forking\n");
        break;
    default:

        // in the father
        childrenPids[i] = currentPid; // store current child pid
        wait(NULL);

这个wait电话打错地方了。如果子节点输出的数据多于管道一次可以容纳的数据,则您在这里出现死锁(子节点将阻塞write,等待父节点read为管道提供一些数据,然后才能退出;父节点将阻塞wait,等待管道孩子在从管道读取之前退出)。

在你给它做任何事情之前等待孩子退出也是没有意义的。这不应该是一种类似协同处理的设计,即孩子应该继续沿着父母运行,根据请求进行算术并将结果发回吗?

        printf("\nParentpid:  %d, Childpid: %i \n", getpid(), currentPid);

        //close(p[1]);

为什么这个被close注释掉了?父进程关闭管道的写入端至关重要(因为否则从管道的读取端读取将阻塞,因为写入端仍然在某处打开(在这种情况下,在同一进程中))。

        if(read(p[0], &val, sizeof(val) == -1){

这一行甚至没有编译。它缺少一个).

            perror("read()\n");
            exit(1);
        }

您缺少对 EOF 的检查。read到达数据末尾时将返回 0(并保持val未初始化)。

您应该使用管道中的所有可用数据(直到read返回0),然后才使用waitpid(currentPid, NULL, 0);.


推荐阅读