C language to create multiple processes (Linux environment)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/mrtwenty/article/details/98848934

fork can be used to create a process, when we are in a loop, you can fork several times, creating multiple processes, but because the fork is executed with multi-process, often surprising happens, consider the following demo:

#include <stdio.h>  //标准的输入输出函数
#include <stdlib.h> //standard library标准库函数头文件
#include <unistd.h> //对于类 Unix 系统,unistd.h 中所定义的接口通常都是大量针对系统调用的封装 fork、

int main()
{
    pid_t pid;
    int i;
    for (i = 0; i < 5; ++i)
    {
        pid=fork();
        // 这是异常情况
        if (pid==-1)
        {
            perror("fork失败!");
            exit(1);
        }
    }

    //返回大于0的进程就是父进程
    if(pid>0)  //父进程
    {
        printf("父进程: pid= %d , ppid=%d,子进程: %d \n", getpid(),getppid(),pid);
        sleep(1); //这里延迟父进程程序,等子进程先执行完。
    }
    else if(pid==0)  //子进程
    { 
        printf("i的变量是: %d 子进程: pid= %d , ppid=%d \n", i,getpid(),getppid());
    }

    return 0; //养成好习惯,返回程序执行状态码
}

After performing compile, execute output, / a.out, the output results are as follows:

A total of 32 out of the process, originally wanted to create five child processes, and why?

The reason is that after the fork, the loop will be executed for the logic in the child, so that it becomes a sub-process will fork a child process, the child process cycle again will create a child process, if repeated five times, is exponential increasing, so is the power of 5, 32 processes 2.

This is not the result we want, so it is necessary to avoid the child process to continue fork

#include <stdio.h>  //标准的输入输出函数
#include <stdlib.h> //standard library标准库函数头文件
#include <unistd.h> //对于类 Unix 系统,unistd.h 中所定义的接口通常都是大量针对系统调用的封装 fork、

int main()
{
    pid_t pid;
    int i;
    for (i = 0; i < 5; ++i)
    {
        pid=fork();
        // 这是异常情况
        if (pid==-1)
        {
            perror("fork失败!");
            exit(1);
        }

        //循环中,fork函数调用五次,子进程返回0,父进程返回子进程的pid,
        //为了避免子进程也fork,需要判断并break
        if (pid==0)
        {
            break;
        }
    }

    //返回大于0的进程就是父进程
    if(pid>0)  //父进程
    {
        printf("父进程: pid= %d , ppid=%d,子进程: %d \n", getpid(),getppid(),pid);
        sleep(1); //这里延迟父进程程序,等子进程先执行完。
    }
    else if(pid==0)  //子进程
    { 
        printf("i的变量是: %d 子进程: pid= %d , ppid=%d \n", i,getpid(),getppid());
    }

    return 0; //养成好习惯,返回程序执行状态码
}

After performing compile, execute output, / a.out, the output results are as follows:

These are learning linux programming based on the book notes.

Guess you like

Origin blog.csdn.net/mrtwenty/article/details/98848934