Unix/Linux如何创建一个后台进程


在Unix/Linux中创建一个后台进程的步骤

1、调用fork函数,创建一个子进程。

2、先让父进程自然结束。

3、在子进程中调用setpgrp(),把子进程的进程组ID设为子进程的进程ID。

4、在子进程中调用setsid(),创建一个新的Session(会话),这样子进程就与当前的控制终端脱离,也接受不到当前终端的(ctrl + c)消息。

实现代码如下(运行环境:虚拟机下的Ubuntu):

  1. /* 
  2.  * Author: ACb0y 
  3.  * FileName: main.cpp 
  4.  * Create Time: 2011-07-24 
  5.  * Version: V1.0 
  6.  */  
  7. #include <iostream>   
  8. #include <unistd.h>   
  9. using namespace std;  
  10.   
  11. void print()   
  12. {  
  13.     int pid = getpid();  
  14.     int gid = getpgid(0);  
  15.     cout << "process group id = " << gid << endl;  
  16.     cout << "process id = " << pid << endl;  
  17. }  
  18.   
  19. int main()   
  20. {  
  21.     //create a child process.   
  22.     int pid = fork();  
  23.     if (-1 == pid)   
  24.     {  
  25.         cout << "call function fork() error!" << endl;  
  26.     }  
  27.     else if (0 == pid)  //return from child process.   
  28.     {  
  29.         cout << "----------in child process.----------" << endl;  
  30.         print();  
  31.         cout << "--------------------------------------" << endl;  
  32.         //将该进程的进程组ID设置为该进程的进程ID。   
  33.         setpgrp();  
  34.         cout << "----------in child process. setpgrp()----------" << endl;  
  35.         print();  
  36.         cout << "--------------------------------------" << endl;  
  37.         //创建一个新的Session,断开与控制终端的关联。也就是说Ctrl+c的触发的SIGINT信号,该进程接收不到。   
  38.         setsid();  
  39.   
  40.       
  41.         for (int i = 0; i < 5; ++i)   
  42.         {  
  43.             sleep(20);  
  44.             cout << "----------in child process.----------" << endl;  
  45.             print();  
  46.             cout << "--------------------------------------" << endl;  
  47.         }  
  48.     }  
  49.     else            //return from parent process.   
  50.     {  
  51.         cout << "----------in parent process.----------" << endl;  
  52.         print();  
  53.         cout << "--------------------------------------" << endl;  
  54.     }  
  55.     return 0;  
  56. }  

相关内容