wait函数使用

wait使用:

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

int main()
{
    pid_t pid = fork();
    if(pid == 0)
    {
          /* child process*/
        printf("child id:%d ppid:%d\n", getpid(), getppid());
        sleep(10);
    }
    else
    {
        /* father process */
        int i = 0;
        while(1)
        {
            if(i == 3)
            {
                break;
            }
            sleep(1);
            printf("father id:%d ppid:%d\n", getpid(),getppid());
            i++;
        }
         /* 等待儿子死掉,好给儿子收尸 */
         printf("call wait return value:%d\n",wait(NULL));
    }
    return 0}

waitpid:

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

int main()
{
    pid_t pid = fork();
    if(pid == 0)
    {
    /* child process*/
        printf("child id:%d ppid:%d\n", getpid(), getppid());
        sleep(10);
    }
    else
    {
        /* father process */
        while(1)
        {
            sleep(1);
            printf("father id:%d ppid:%d\n", getpid(),getppid());
            /*  非阻塞回收子进程 */
            if(0 != waitpid(0,NULL,WNOHANG))
            {
                break;
            }
        }
    }
    return 0}

猜你喜欢

转载自blog.csdn.net/weixin_42411048/article/details/106955303
今日推荐