zoukankan      html  css  js  c++  java
  • Linux学习笔记16——wait函数

    wait函数的定义如下:

    #include <sys/types.h>
    #include <sys/wait.h>
    pid_t wait(int *stat_loc);

      wait系统调用将暂停父进程直到它的子进程结束为止,这个调用返回子进程的PID,它通常是已经结束运行的子进程的PID。状态信息允许父进程了解子进程的退出状态,即子进程的main函数返回的值或子进程中exit函数的退出码。如果stat_loc不是空指针,状态信息将被写入它所指向的位置。

      状态信息如下:WIFEXITED(stat_val)      如果子进程正常结束,它就取一个非零值
             WEXITSTATUS(stat_val)      如果WIFEXITED非零,它返回子进程的退出码
             WIFSIGNALED(stat_val)      如果子进程因为一个未捕获的信号而终止,它就取一个非零值
             WTERMSIG(stat_val)      如果WIFSIGNALED非零,它返回一个信号代码
             WIFSTOPPED(stat_val)     如果子进程意外终止,它就取一个非零值
             WSTOPIG(stat_val)         如果WIFSTOPPED非零,它返回一个信号代码

    #include <sys/types.h>
    #include <sys/wait.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(){
        pid_t pid;
        char *message;
        int n;
        int exit_code;
        
        printf("fork program starting
    ");
        pid=fork();
        switch(pid){
            case -1:
                perror("fork failed");
                exit(1);
            case 0:
                message="This is the child";
                n=5;
                exit_code=37;
                break;
            default:
                message="This is the parent";
                n=3;
                exit_code=0;
                break;
        }
        for(;n>0;n--){
            puts(message);
            sleep(1);
        }
        //这一部分等待子进程完成
        if(pid != 0){
            int stat_val;
            pid_t child_pid;
         printf("stat_val is:%d ",stat_val); child_pid
    =wait(&stat_val);           //子进程的ID
         printf("stat_val is:%d ",stat_val);
    printf(
    "Child has finished:PID=%d ",child_pid); if(WIFEXITED(stat_val)){    //如果子进程正常退出 printf("Child exited with code %d ",WEXITSTATUS(stat_val)); } else{ printf("Child terminated abnormally "); } } exit(exit_code); }

    输出结果如图:

  • 相关阅读:
    JavaScript连等赋值
    vue入坑总结
    form表单与后台请求的关系
    JavaScript构造函数、继承的理解
    前端知识未学习点
    js垃圾回收机制
    前端闭包
    html中strong与b,em与i标签的区别(转帖)
    Docker 搭建开源跳板机_jumpserver (运维开源堡垒机_jumpserver) Centos_7.0
    python EasyUI + Django--整合 CSRF 防护去除
  • 原文地址:https://www.cnblogs.com/zjzsky/p/3495439.html
Copyright © 2011-2022 走看看