[英]Using Fork() and Pipe() to sum a file split to multiple child processes
[英]Setting up four processes with fork() using 1 pipe
尝试编写一个简单的程序,使用管道/叉子创建/管理1个父进程和4个孩子进程。 父进程应该像这样显示一个主菜单。
Main Menu:
1. Display children states
2. Kill a child
3. Signal a child
4. Reap a child
5. Kill and reap all children
我现在正在编写的代码应该创建4个子进程。 我不确定是否正确设置了四个子进程。 我了解fork向子级返回0,向父级返回PID。 如何访问这些PID值的父级? 我在哪里为父流程设置菜单?
#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);
}
}
}
我的输出是:
Child 1: pid: 0
Child 2: pid: 0
Child 3: pid: 0
Child 4: pid: 0
我不确定是否正确设置了四个子进程。
是的,你不应该让孩子们脱离他们的代码块,所以改变
break;
至
sleep(99); // or whatever you want the child to do
exit(0);
我如何访问父母……?
有getppid() ,如果出于某种原因您需要它。
我在哪里为父流程设置菜单?
在main
结束之前的for
循环之后执行操作,这是父级继续执行的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.