Linux programming fork()

Fork() creates a child process
    that fails to create a negative value
        and returns a different error code (errno), EAGAIN (limit on the number of system processes), ENOMEM (failed to apply for memory), ENOSYS (not supported by the system platform).
    Successful creation will return two values
        = 0; the return value of the child process indicates that the current program is running in the child process
        > 0; the return value of the parent process indicates that the current program is running in the parent process, and the return value is the PID value of the child process


wait() The parent process blocks and waits for the status change of the child process, usually used with fork.

Brief example:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>

int main()
{
    pid_t ret;
    int wstatus;
    
    ret = fork();
    if(ret > 0)
    {
        //父进程执行
        printf("it is father %d,ret=%d\n",getpid(),ret);
    }
    else if(ret == 0)
    {
        //子进程执行
        printf("it is child %d,ret=%d\n",getpid(),ret);
    }
    else
    {
        //创建进程失败,父进程执行
        printf("fork return error,ret=%d\n",ret);
    }

    //子父进程都会执行
    printf("my pid is %d.\n",getpid());
    while(1)
    {
        if(-1 != wait(&wstatus))
        {
            printf("%d process's child killed.\n",getpid());
            break;
        }
        sleep(1);
    }
    return 0;
}

Results of the:

Execute ps axf to see the relationship between the two processes

Use the kill command to kill the child process, then wait () can capture the state of the child process changes

Guess you like

Origin blog.csdn.net/qq_36413391/article/details/110872384