一个创建子进程的简单示例代码

参考APUE中第1章1.6小节

主要涉及到2个函数: fork、exec

 

  1. // filename : process_ctrl.c  
  2. // child process -- fork, exec, waitpid  
  3.   
  4. #include <stdio.h>  
  5. #include <sys/wait.h>  
  6.   
  7. #define MAXLINE 32  
  8.   
  9.   
  10. int main(int argc, char *argv[])  
  11. {  
  12.     char     buf[MAXLINE];  
  13.     pid_t     pid;  
  14.     int     status;  
  15.   
  16.     printf("parent: pid=%d ", getpid());  
  17.     printf("%% ");  
  18.   
  19.     while (fgets(buf, MAXLINE, stdin) != NULL)  
  20.     {  
  21.         if (buf[strlen(buf) - 1] == ' ')  
  22.             buf[strlen(buf)-1] = 0;  
  23.           
  24.         pid = fork();  
  25.           
  26.         if (pid < 0)  
  27.         {  
  28.             printf("parent: fork() error! ");  
  29.         }  
  30.         else if (pid == 0)  
  31.         {  
  32.             printf("child: new process start! ");  
  33.             printf("child: new process pid=%d ", getpid());  
  34.             execlp(buf, buf, (char *)0);  
  35.             printf("child: couldn't execure: %s ", buf);  
  36.             exit(1);  
  37.         }  
  38.         else  
  39.         {  
  40.             printf("parent: child process pid=%d ", pid);  
  41.         }  
  42.   
  43.         if ((pid = waitpid(pid, &status, 0)) < 0)  
  44.             printf("waitpid error ");  
  45.         printf("%%");  
  46.     }  
  47. }  

运行结果:

 

[plain] view plaincopy在CODE上查看代码片派生到我的代码片
  1. %[mht@localhost p1_5]$ ./process_ctrl   
  2. parent: pid=6922  
  3. % ls  
  4. child: new process start!  
  5. child: new process pid=6927  
  6. process_ctrl  process_ctrl.c  
  7. parent: child process pid=6927  
  8. %  
原文地址:https://www.cnblogs.com/haichun/p/3522807.html