c - 关于父进程使用简单管道向子进程写入消息的说明
问题描述
这是一个 C 程序,其中父进程尝试使用简单的管道将消息写入其子进程。得到预期的输出。
根据代码,父进程调用wait(),一直等到子进程退出(返回)。
另外,子进程调用read(),它等待通过另一个管道端写入一些东西?
因此,两个进程不应该一直相互等待并导致死锁吗?该程序如何正常运行?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MSGSIZE 16
char *msg1 = "Hello,Once";
char *msg2 = "Hello,Twice";
char *msg3 = "Hello,Thrice";
int main()
{
char buff[MSGSIZE];
int pi[2],pid,nbytes;
if(pipe(pi) < 0) _exit(1);
if((pid=fork()) > 0)
{
close(pi[0]);
write(pi[1],msg1,MSGSIZE);
write(pi[1],msg2,MSGSIZE);
write(pi[1],msg3,MSGSIZE);
close(pi[1]);
wait(NULL);
}
else
{
close(pi[1]);
while((nbytes = read(pi[0],buff,MSGSIZE)) > 0) printf("%s\n",buff);
printf("Reading Completed\n");
close(pi[0]);
if(nbytes != 0) _exit(2);
}
return 0;
}
解决方案
推荐阅读
- regex - UNIX 从 JSON SED/AWK 获取 5 分钟前的事务
- c# - 构建一个在没有 C++ Redistributable Package 的情况下运行的 .exe
- tcp - 多个 modbus 从站的模拟器
- scala - 使用 Scala 数据帧中的分区创建配置单元表
- javascript - 模拟 DOM 方法笑话
- python - IntegrityError:唯一约束失败:my_films.title_id
- java - 为什么 SoundPool 不会自动路由到连接的耳机?
- facebook - Facebook SDK:即使授予了权限,client_pages 调用也会返回“PENDING”
- java - How to get length and isEmpty methods as a return value to get method used for my Circular Linked List?
- c# - 如何使用计时器来查看 C# 中的等式需要多长时间