• wait函数


    当一个进程正常或异常终止时,内核就向其父进程发送SIGCHLD信号。子进程终止是一个异步事件(其能够在父进程运行的任何时候发生)。

    对于wait(),其调用者,即父进程可以有如下状态:

    • 如果其所有子进程都还在运行,则阻塞;
    • 如果一个子进程已终止,正等待父进程获取其终止状态,则取得该子进程的终止状态后立即返回;
    • 如果它没有任何子进程,则立即出错返回;

    代码测试:

     1 #include <stdio.h>
     2 #include <unistd.h>
     3 #include <stdlib.h>
     4 
     5 int main(void)
     6 {
     7     pid_t pid_f = getpid();
     8     pid_t pid_c;
     9     pid_f = fork();
    10     if(pid_f < 0) {
    11         printf("fork error
    ");
    12     }
    13     else if(pid_f == 0) {
    14         printf("child process start
    ");
    15         sleep(10);
    16     }
    17     else {
    18         printf("father process goes on
    ");
    19         wait(NULL);
    20         printf("child process exited
    ");
    21     }
    22     printf("wait for child exit %d
    ",pid_f);
    23     return 0;
    24 }

    执行结果:

    最初执行:

    root@ubuntu:/home/test# ./wait_test
    father process goes on
    child process start

     父进程创建子进程后,调用wait(),发生阻塞,等待一个子进程退出;子进程休眠10秒后执行后续操作。

    10秒后:

    root@ubuntu:/home/test# ./wait_test
    father process goes on
    child process start
    wait for child exit 0
    child process exited
    wait for child exit 6038

    子进程休眠结束后,输出“wait for child exit 0”,其进程号表明其为子进程输出结果。父进程输出“wait for child exit 6038”,其进程号表明其为父进程输出结果。

  • 相关阅读:
    linux开发板出现Read-only file system的解决办法
    nginx源码分析之网络初始化
    nginx源码分析之hash的实现
    hdu4833 Best Financing(DP)
    PHP读取office word文档内容及图片
    nginx+uwsgi+bottle python服务器部署
    创建、托管和浏览文档
    python非官方扩展库
    simplexml_load_string 转换xml为数组
    PHPExcel 导出数据(xls或xlsx或csv)- 助手类(函数)
  • 原文地址:https://www.cnblogs.com/scu-cjx/p/7723817.html
Copyright © 2020-2023  润新知