fork_test.c

来自「1、 了解系统调用fork()、execl()、exit()、getpid()和」· C语言 代码 · 共 29 行

C
29
字号
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
main()
{ 
   pid_t pid;
   int i =2;
   printf("The main process is printing:id is %d\n",getpid());
   switch (pid = fork())
   {
    case -1:
     perror("the fork failed!\n");
     break;
    case 0: //pid为0,子进程。
     printf("The child'getpid is %d\n",getpid());
     printf("The child is calling an exec.the child'pid is %d\n",pid);
     execl("/bin/ps", "/bin/ps", "-a" , NULL);
     _exit(0);

    default://pid大于0,为父进程得到的子进程号
     printf("The parent is waiting for child to exit.the id is %d.\n",getpid());
     waitpid(pid, NULL, 0);
     printf("child has exited.\n");
     printf("Parent had exited.\n");

   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?