您的位置:首页 > 大数据 > 人工智能

fork wait

2016-05-12 21:47 495 查看
#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/wait.h>

#include <fcntl.h>

//daemon   

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

{

    int num = argc;

    int i=0;

    int status = 0;

    int fd = -1;

//    printf("num is %d\n",num);//line Cache need \n to output

//    for(i=0; i < num; i++)

//    {

//      printf("argv %d:%s\n",i,argv[i]);       

//    }

    pid_t old_pid = getpid();

    pid_t new_pid = fork();

    if (new_pid > 0)

    {

        printf ("father pid %d,%d\n",getppid(), getpid() );

        _exit(0);

    }

    else if (new_pid == 0)

    {

        printf("child pid %d,%d\n",getppid(), getpid() );

    }

    //std io -> dev/null

    //if (-1 != (fd = open( "/dev/null", O_RDWR, 0)))

    //{

        //dup2(fd, STDIN_FILENO);

        //dup2(fd, STDOUT_FILENO);

        //dup2(fd, STDERR_FILENO);

        //if (2 < fd)

        //{

            //close(fd);

        //}

    //}  

    if (-1 == setsid())

    {

        printf("error");

        return (-1);

    }

    (void)chdir("/");

    pid_t second_child = fork();

    if (0 < second_child)

    {

        printf("second child pid %d,%d\n",getppid(), getpid() );

        while (0 == status)

        {
            pid_t dead_pid = wait(&status);

            printf("dead pid=%d\n",dead_pid);

            int exitStatus = (int) WEXITSTATUS (status);

            printf("Child Process %d wait exited with pid=%d status=%d exit status=%d\n",getpid(), dead_pid, status, exitStatus);

        }

    }

    else if (0 == second_child)

    {

        printf("grandson pid %d,%d\n",getppid(), getpid() );

        sleep (5);

  //      exit(7);

    }

    while (1);

    return 1;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: