1. Call the fork function to create a child process. 2, first let the parent process end naturally. 3, call SETPGRP () in the child process, the process group ID of the processing process is set to the process ID of the child process. 4, call Setsid () in the child process, create a new session, this way the process is detached from the current control terminal, and can not accept the current terminal (CTRL + C) message.
1#include <iostream>2#include <unistd.h>3 using namespacestd;4 5 voidprint ()6 {7 intPID =getpid ();8 intGID = Getpgid (0);9cout <<"Process Group id ="<< GID <<Endl;Tencout <<"Process id ="<< PID <<Endl; One } A - intMain () - { the //Create a child process. - intPID =fork (); - if(-1==pid) - { +cout <<"Call function fork () error!"<<Endl; - } + Else if(0= = pid)//Return from the child process. A { atcout <<"----------in the child process.----------"<<Endl; - print (); -cout <<"--------------------------------------"<<Endl; - //Set the process group ID of the process to the process ID of the process . - setpgrp (); -cout <<"----------in child process. SETPGRP ()----------"<<Endl; in print (); -cout <<"--------------------------------------"<<Endl; to //create a new session and disconnect from the control terminal. That is to say CTRL + C trigger the SIGINT signal, the process is not received. + Setsid (); - the * for(inti =0; I <5; ++i) $ {Panax NotoginsengSleep -); -cout <<"----------in the child process.----------"<<Endl; the print (); +cout <<"--------------------------------------"<<Endl; A } the } + Else //return from parent process. - { $cout <<"----------in parent process.----------"<<Endl; $ print (); -cout <<"--------------------------------------"<<Endl; - } the return 0; -}
How to create a background process