📌  相关文章
📜  在C中使用fork()从同一父进程创建n子进程

📅  最后修改于: 2021-05-28 02:07:46             🧑  作者: Mango

fork()是一个系统调用函数,可以从父主进程生成子进程。使用某些条件,我们可以根据需要生成尽可能多的子进程。

我们给了n,我们必须从相同的父进程(主进程)创建n个子进程。

例子:

Input :3
Output :[son] pid 25332 from [parent] pid 25329
        [son] pid 25331 from [parent] pid 25329
        [son] pid 25330 from [parent] pid 25329

here 25332, 25331,25330 are child processes from same parent process
with process id 25329 

Input :5
Output :[son] pid 28519 from [parent] pid 28518
        [son] pid 28523 from [parent] pid 28518
        [son] pid 28520 from [parent] pid 28518
        [son] pid 28521 from [parent] pid 28518
        [son] pid 28522 from [parent] pid 28518

here 28519, 28519,28520,28521,28522 are child processes from same parent process
with process id 28518 

#include
  
  
int main()
{
    for(int i=0;i<5;i++) // loop will run n times (n=5)
    {
        if(fork() == 0)
        {
            printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid());
            exit(0);
        }
    }
    for(int i=0;i<5;i++) // loop will run n times (n=5)
    wait(NULL);
      
}

输出:

[son] pid 28519 from [parent] pid 28518
[son] pid 28523 from [parent] pid 28518
[son] pid 28520 from [parent] pid 28518
[son] pid 28521 from [parent] pid 28518
[son] pid 28522 from [parent] pid 28518

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。