简体   繁体   English

在C中处理多个fork()

[英]Handling multiple fork()s in c

I'm struggling to understand this concept. 我正在努力理解这个概念。 Let's say I want to run 3 concurrent processes (threads are not an option, this is an assignment). 假设我要运行3个并发进程(线程不是一个选择,这是一个分配)。

I would do: 我会做:

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

So from what I've learned the parent pid is -1. 因此,据我了解到,父pid是-1。 And there's two children, both with PID 0? 还有两个孩子,两个孩子的PID均为0?

So then the "parent" can spawn as many children as possible, correct? 那么,“父母”可以生出尽可能多的孩子,对吗? They will all do child things. 他们都会做孩子的事情。

What if I want to do 3 different things? 如果我想做3件事怎么办? How do I track the PID's so that I have 3 unique ones? 如何跟踪PID,以便有3个唯一的PID?

as per the comments - is this how it's done? 根据评论-这是怎么做的?

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
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

The whole idea is that you enter fork() once, but leave it twice - once in the parent, once in the child. 整个想法是,您输入一次fork(),但将其保留两次-一次在父级中,一次在子级中。 In the parent, fork() returns the child's PID, in the child, fork() returns 0. -1 means error and there is no child. 在父级中,fork()返回子级的PID,在子级中,fork()返回0。-1表示错误,没有子级。

So when you call fork(), look at the return value. 因此,当您调用fork()时,请查看返回值。 Like this: 像这样:

  if(fork() > 0) //We're in the parent, and a child was spawned
      fork(); //Spawn another.

This will create three processes. 这将创建三个过程。 Error handling omitted. 省略错误处理。

** int main() { pid_t pid; ** int main(){pid_t pid; int i; for(i = 0;i < 3;i++) { pid = fork(); for(i = 0; i <3; i ++){pid = fork(); } }

if(pid == 0)
{
    printf("child\n");        
}
else if(pid > 0)
{
    printf("parent\n");
}

return 0;
}

you can use pid_t = fork() to record the value,and select what you do by the value.** 您可以使用pid_t = fork()来记录值,并根据值选择要执行的操作。**

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM