• wait函数与waitpid函数的区别


    #include

    #include

    pid_t wait(int *wstatus);  //等待任意子进程结束,并给子进程收尸

    参数: 获取子进程退出状态,NULL则表示忽略子进程退出状态

    返回值:

          成功: 收尸的子进程的进程号

    失败: -1, 并设置errno

        WIFEXITED(wstatus) --- 当子进程正常退出时,返回为真

        WEXITSTATUS(wstatus) --- 当子进程正常退出时,返回子进程退出值

    pid_t waitpid(pid_t pid, int *wstatus, int options); //功能:等待指定的子进程结束,并收尸(阻塞和非阻塞)

    参数:

        pid

          >0: 只等待进程ID等于pid的子进程

            -1:等待任何一个子进程退出,此时和wait作用一样。

            0:等待其组ID等于调用进程的组ID的任一子进程。

            <-1:等待其组ID等于pid的绝对值的任一子进程。

        wstatus:同wait

       options:

         WNOHANG:若由pid指定的子进程没有退出,则waitpid不阻塞,此时返回值为0

         0: 同wait

    返回值:

       <0: 失败,设置errno

       =0:非阻塞返回,并且没有收到尸体

       >0: 收到的子进程的进程号

    wait的代码:

    #include
    #include
    #include
    #include
    #include

    int main(int argc, char *argv[])

        pid_t pid = fork();
        if (pid < 0)
        {
            perror("fork");
            return -1;
        }
        else if (0 == pid) //child
        {
            sleep(1);
            printf("child: pid = %d\n", getpid());
            exit(10);
        }
        printf("parent!\n");
        //pid = wait(NULL);
        int wstatus;
        pid = wait(&wstatus);  //获取子进程退出状态
        if (WIFEXITED(wstatus))  //判断是否是正常退出
        {
            printf("Child process exit normally!\n");
            printf("exit: %d\n", WEXITSTATUS(wstatus)); //获取退出值
        }
        else
            printf("Chils process exit unnormally!\n");
        printf("wait: pid = %d\n", pid);

        return 0;

     

    waitpid代码如下:

    #include
    #include
    #include
    #include
    #include

    int main(int argc, char *argv[])

        pid_t pid = fork();
        if (pid < 0)
        {
            perror("fork");
            return -1;
        }
        else if (0 == pid) //child
        {
            sleep(1);
            printf("child: pid = %d\n", getpid());
            exit(0);
        }
        printf("parent!\n");
        sleep(2);
     // pid = waitpid(-1, NULL, 0);  //阻塞等待任意子进程退出,获取子进程退出状态
        pid = waitpid(-1, NULL, WNOHANG);  //非阻塞等待任意子进程退出,获取子进程退出状态
        if (0 > pid)
        {
            perror("waitpid");
            return -1;
        }
        else if (0 == pid)
            printf("No such child process exit!\n");
        else
            printf("wait: pid = %d\n", pid);

        return 0;

     

  • 相关阅读:
    项目整合flyway实现数据脚本的自动更新
    卷积神经网络 - LeNet
    双目3D感知(一):双目初步认识
    el-table 表格从下往上滚动,触底自动请求新数据
    【测试沉思录】11. 如何进行基准测试?
    Redisson之lock()和tryLock()的区别
    flink MemoryStateBackend 和 RocksDBStateBackend 切换导致任务出现bug
    【前端】在Vue页面中引入其它vue页面 数据传输 相互调用方法等
    Kinodynamic RRT-connect(Rapidly-exploring Random Tree-Connect)算法例子
    lenovo联想笔记本小新 潮7000-14IKBR 2018款(81GA)原装出厂Windows10系统镜像
  • 原文地址:https://blog.csdn.net/qq_63626307/article/details/126507285