在 c 中处理多个 fork()

Bry*_*son 1 c

我正在努力理解这个概念。假设我想运行 3 个并发进程(线程不是一个选项,这是一个分配)。

我会做:

int main(){
    fork();
    if (getPid() == -1) { //this is the parent
        fork(); //make a third process
    } else if (getPid() == 0) { //child process
    //do child things
    }
Run Code Online (Sandbox Code Playgroud)

所以从我了解到的父 pid 是 -1。有两个孩子,PID 都是 0?

那么“父母”可以产生尽可能多的孩子,对吗?他们都会做孩子的事情。

如果我想做 3 件不同的事情怎么办?我如何跟踪 PID 以便我有 3 个独特的?

根据评论 - 这是如何完成的?

pid_t child2Pid;
pid_t child1Pid = fork();
switch /*if getPid is wrong what do I put here?*/ {
case -1: //parent
    child2Pid = fork(); //create another child
case child1Pid :
    //do what child1 would do
case child2Pid :
    //do what child2 would do
Run Code Online (Sandbox Code Playgroud)

Dav*_*rtz 5

pid_t child1, child2, child3;
if ((child1 = fork()) == 0)
{
    // first child stuff goes here
    _exit(0);
}
if ((child2 = fork()) == 0)
{
    // second child stuff goes here
    _exit(0);
}
if ((child3 = fork()) == 0)
{
    // third child stuff goes here
    _exit(0);
}
// we are in the parent, we have the PIDs of our three
// children in child1, child2, and child3
Run Code Online (Sandbox Code Playgroud)