是什么导致我的程序挂起并且不能正常退出?(管道,读取系统调用,while 循环) [英] What is causing my program to hang and not exit properly? (pipe, read system call, while loop)

查看:74
本文介绍了是什么导致我的程序挂起并且不能正常退出?(管道,读取系统调用,while 循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,我从几个子进程写入一个管道,然后尝试从每个管道读取写入每个进程的所有消息,并将它们打印到屏幕上.使用以下代码(特别是使用 read 系统调用将消息存储到缓冲区 buf 的 while 循环),我的程序将挂起而不退出,也不打印所有发送到不同进程的消息.

I have a program where I write from several child processes to a pipe, and then attempt to read all the messages written to each process, from each pipe, and print them to the screen. With the following code (specifically, the while loop using the read system call to store the messages into buffer buf), my program will hang and not exit, nor print all of the messages sent to the different processes.

for (i = 0; i < MAXP; i++) {
    if(id == i) {
        while(read(pfds[i][0], buf, sizeof(buf)) > 0)
             printf("process%d has received a message from %s\n",i,buf);    
    }
}

但是,使用以下代码,程序可以正确退出,但不会打印所有消息(因为它们并未全部读取):

However, with the following code, the program exits correctly, but does not print all the messages (as they aren't all read):

for (i = 0; i < MAXP; i++) {
    if(id == i) {
        nbytes = read(pfds[i][0], buf, sizeof(buf));
        printf("process%d has received a message from %s\n",i,buf); 
    }
}

这是我写入管道的代码:

This is my code writing to the pipes:

write(pfds[j][1],msg,9);  // write the message to j pipe

消息是:

sprintf(msg, "process%d", i); // create the message - 9 bytes (inc. null term)
// the message is "process0" or "process1" ... through "process8"

这是一个 9 字节的字符数组:

which is a 9 byte char array:

char msg[9];

解决方案

for (j = 0; j < MAXP; j++) {
    close(pfds[j][1]); // close write to j from i
}

推荐答案

也许 b/c 你没有关闭管道?如果写端没有关闭,读将继续挂起

Maybe b/c you didn't close the pipe? if write end is not closed, read will keep on hanging

尝试添加

close(pfds[j][1]);

在您将信息写入管道后

这篇关于是什么导致我的程序挂起并且不能正常退出?(管道,读取系统调用,while 循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆