Multiple child process

前端 未结 4 1527
死守一世寂寞
死守一世寂寞 2020-12-01 01:59

can someone help me about how to create multiple child processes which have the same parent in order to do \"some\" part of particular job?

for example, an external

4条回答
  •  时光说笑
    2020-12-01 02:07

    If you want to launch several forks, you should do it recursively. This is because you must call fork from the parent process. Otherwise, if you launch a second fork, you will duplicate both parent and first child process. Here's an example:

    void forker(int nprocesses)
    {
        pid_t pid;
    
        if(nprocesses > 0)
        {
            if ((pid = fork()) < 0)
            {
                perror("fork");
            }
            else if (pid == 0)
            {
                //Child stuff here
                printf("Child %d end\n", nprocesses);
            }
            else if(pid > 0)
            {
                //parent
                forker(nprocesses - 1);
            }
        }
    }
    

提交回复
热议问题