[英]Setting up four processes with fork() using 1 pipe
Trying to write a simple program that uses pipe/fork to create/manage 1 parent and 4 kid processes. 尝试编写一个简单的程序,使用管道/叉子创建/管理1个父进程和4个孩子进程。 The parent process is supposed to display a main menu like so.
父进程应该像这样显示一个主菜单。
Main Menu:
1. Display children states
2. Kill a child
3. Signal a child
4. Reap a child
5. Kill and reap all children
The code I'm writing now is supposed to create 4 child processes. 我现在正在编写的代码应该创建4个子进程。 I'm unsure if I'm setting up the four child processes correctly.
我不确定是否正确设置了四个子进程。 I understand fork returns 0 to the child and the PID to the parent.
我了解fork向子级返回0,向父级返回PID。 How do I access the parent for these PID values?
如何访问这些PID值的父级? Where exactly do I set up the menu for the parent process?
我在哪里为父流程设置菜单?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#define BUFSIZE 1024
#define KIDS 4
main()
{
//create unnamed pipe
int fd[2];
char buf[BUFSIZE];
if (pipe(fd) < 0)
{
perror("pipe failed");
exit (1);
}
//array of child pids
size_t child_pid[4];
//create 4 proccesses
int i = 0;
for (i = 0; i < KIDS; i++) {
child_pid[i] = fork();
if (child_pid[i]) {
continue;
} else if (child_pid[i] == 0) {
close(fd[0]);
printf("Child %d: pid: %zu", i+1, child_pid[i]);
break;
} else {
printf("fork error\n");
exit(1);
}
}
}
My output is: 我的输出是:
Child 1: pid: 0
Child 2: pid: 0
Child 3: pid: 0
Child 4: pid: 0
I'm unsure if I'm setting up the four child processes correctly.
我不确定是否正确设置了四个子进程。
Right, you shouldn't let the children break out of their code block, so change 是的,你不应该让孩子们脱离他们的代码块,所以改变
break;
to 至
sleep(99); // or whatever you want the child to do
exit(0);
How do I access the parent …?
我如何访问父母……?
There's getppid() , if for some reason you need it. 有getppid() ,如果出于某种原因您需要它。
Where exactly do I set up the menu for the parent process?
我在哪里为父流程设置菜单?
Do that after the for
loop before the end of main
, that's where the parent continues execution. 在
main
结束之前的for
循环之后执行操作,这是父级继续执行的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.