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

http://www.linuxidc.com/Linux/2011-07/39587.htm


在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;  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值