Wait for synchronization between Linux processes

1. About the system-level function wait

1. Function

    Realize process synchronization.

    When the child process is executing, wait() can suspend the execution of the parent process and make it wait. Once the child process is executed, the waiting parent process will be re-executed. If there are multiple child processes executing , wait() in the parent process returns when the first child process ends, and the parent process execution is resumed.

2. Function information

Header file: sys/wait.h

Function signature: pid_t wait(int *status)

Description:

     Formal parameter: If status is a pointer to an integer, when wait returns, the pointer points to the status information when the child process exits.

                If status is a null pointer, wait will ignore this parameter.

     Return value: -1, indicating that no child process ends; others, indicating the process identifier of the ended child process.

3. Usual usage

    The parent process calls fork() after the child process calls wait(). The following example:

pid=fork();
if (!pid)
{
    /* 子进程 */
} 
else 
{
    /* 父进程 */
    wait(NULL);
}

Two, chestnuts

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

int main()
{
    pit_t pid = -1;

    if((pid = fork()) < 0)
    {
        perror("fork failed");
        return 1;
    }

    if (!pid)
    { // 子进程
        sleep(4);
        return 5; 
    }
    else  // 父进程
    {
        int status = 0;
        if (wait(&status) < 0)
        {
            perror("wait failed");
            return 1;
        }

        if (status & 0xFF)
        {
            printf("Somne low-roderbits not zero\n");
        }
        else 
        {
            int exit_status = 0;
            exit_status=status >> 8;
            exit_status &= 0xFF;
            printf("Exit status from pid[%d] was exit_status[%d]\n", pid, exit_status);
        }
    }

    return 0;
}   

Execution output: Exit status from pid[2] was exit_status[5]

Note: The pid value may be different in different environments.

Guess you like

Origin blog.csdn.net/xunye_dream/article/details/113729601