c - 您可以选择哪个子进程从父进程接收消息吗?
问题描述
下面我有一个父进程的代码,它创建了两个属于它的子进程。现在,我知道我可以做到这一点,以便父进程可以写入子进程,而子进程可以使用 read() 和 write() 从中读取。
我的问题是,父母是否可以在下面的代码中选择要写信给哪个孩子?例如,我问程序的用户是否想用他们自己提供的消息写入子进程 1 或子进程 2,我该怎么做?
int p1[2];
int p2[2];
pid_t child_a, child_b;
if(pipe(p1) == -1){
printf("error in creating pipe\n");
exit(-1);
}
if(pipe(p2) == -1){
printf("error in creating pipe\n");
exit(-1);
}
child_a = fork();
if (child_a == 0) {
/* Child A code */
} else {
child_b = fork();
if (child_b == 0) {
/* Child B code */
} else {
/* Parent Code */
}
}
解决方案
您已经创建了两个管道,因此您走在正确的轨道上。例如,您可以使用一个管道p1
将消息从父级发送到child_a
,并使用p2
将消息发送到child_b
。
您可以使用dup2
将标准输入文件描述符切换为
int p1[2];
int p2[2];
pid_t child_a, child_b;
if(pipe(p1) == -1){
printf("error in creating pipe\n");
exit(-1);
}
if(pipe(p2) == -1){
printf("error in creating pipe\n");
exit(-1);
}
child_a = fork();
if (child_a == 0) {
/* Child A code */
// now can read from stdin to receive messages from parent process
dup2(p1[0], STDIN_FILENO);
// don't forget to close file descriptors that are open in every process!
close(p1[0]); close(p1[1]);
} else {
child_b = fork();
if (child_b == 0) {
/* Child B code */
dup2(p2[0], STDIN_FILENO);
close(p2[0]); close(p2[1]);
} else {
/* Parent Code */
// Write something to child A
write(p1[1], some_text, num_bytes);
// Write something to child B
write(p2[1], some_other_text, num_other_bytes);
}
}
请记住,它write
需要一个int
文件描述符、一个void*
要写入的缓冲区——可以是 a char*
,以及int
要写入文件描述符的字节数。
这是write
来自 POSIX API 的文档:https ://linux.die.net/man/2/write
这是文档dup2
:https ://linux.die.net/man/2/dup2
推荐阅读
- android-espresso - 使用“com.android.test”插件构建仪器测试后出错
- raspberry-pi3 - 每 30 秒读取一次的 Arduino-DHT11 库
- python - 如何在 cozmo 机器人和 hololens 之间合并 websocket 连接?
- qt - Qt如何知道动态创建时选择了复选框?
- git - Git撤消推送的提交(错误地删除了文件夹),上面有其他提交
- c# - 错误 CS0649,程序不会在定义的 UI 中显示变量
- c# - 使用不在数据库中的实体对象进行 LINQ 查询 - 错误:LINQ to Entities 无法识别该方法
- python - Seaborn 图表收敛于同一点不可见
- python - 熊猫:最后一次列具有非 nan 值
- javascript - 在 javascript 中覆盖匿名 const 函数