• 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;

     

  • 相关阅读:
    【LeetCode75】第七十二题 无重叠区间
    JSD-2204-(业务逻辑开发)-续消息队列-Kafka-RabbitMQ-Day15
    【数据结构】排序--选择排序(堆排序)
    【LeetCode】1342.将数字变成0的操作次数
    微信小程序 java网上购物商城系统
    EasyCVR通过大华SDK接入设备,通道名称过长显示不全如何解决?
    网络授时服务器(NTP授时系统)售后与安装步骤
    浅谈 synchronized 锁机制原理 与 Lock 锁机制
    用《斗破苍穹》的视角打开C#多线程开发1(斗帝之路)
    Qt-day3
  • 原文地址:https://blog.csdn.net/qq_63626307/article/details/126507285