1、调用fork函数,创建一个子进程。
2、先让父进程自然结束。
3、在子进程中调用setpgrp(),把子进程的进程组ID设为子进程的进程ID。
4、在子进程中调用setsid(),创建一个新的Session(会话),这样子进程就与当前的控制终端脱离,也接受不到当前终端的(ctrl + c)消息。
1 #include <iostream> 2 #include <unistd.h> 3 using namespace std; 4 5 void print() 6 { 7 int pid = getpid(); 8 int gid = getpgid(0); 9 cout << "process group id = " << gid << endl; 10 cout << "process id = " << pid << endl; 11 } 12 13 int main() 14 { 15 //create a child process. 16 int pid = fork(); 17 if (-1 == pid) 18 { 19 cout << "call function fork() error!" << endl; 20 } 21 else if (0 == pid) //return from child process. 22 { 23 cout << "----------in child process.----------" << endl; 24 print(); 25 cout << "--------------------------------------" << endl; 26 //将该进程的进程组ID设置为该进程的进程ID。 27 setpgrp(); 28 cout << "----------in child process. setpgrp()----------" << endl; 29 print(); 30 cout << "--------------------------------------" << endl; 31 //创建一个新的Session,断开与控制终端的关联。也就是说Ctrl+c的触发的SIGINT信号,该进程接收不到。 32 setsid(); 33 34 35 for (int i = 0; i < 5; ++i) 36 { 37 sleep(20); 38 cout << "----------in child process.----------" << endl; 39 print(); 40 cout << "--------------------------------------" << endl; 41 } 42 } 43 else //return from parent process. 44 { 45 cout << "----------in parent process.----------" << endl; 46 print(); 47 cout << "--------------------------------------" << endl; 48 } 49 return 0; 50 }