如何创建一个后台进程
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 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。