我有一个程序,其中将多个子进程写入管道,然后尝试从每个管道读取写入每个进程的所有消息,然后将它们打印到屏幕上。使用以下代码(特别是使用read
系统调用的while循环将消息存储到buffer中buf
),我的程序将挂起且不会退出,也不会打印所有发送到不同进程的消息。
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);
}
}
但是,使用以下代码,该程序可以正确退出,但不会打印所有消息(因为它们并非全部被读取):
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);
}
}
这是我写给管道的代码:
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字节的char数组:
char msg[9];
解
for (j = 0; j < MAXP; j++) {
close(pfds[j][1]); // close write to j from i
}
也许您没有关闭水管?如果写端未关闭,读将继续挂起
尝试添加
close(pfds[j][1]);
在将消息写入管道后
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句