/*************************************** ******************************
* Function: Test daemon process
* Author: Samson
* Date: 11/30/2011
* Test Platform:
* GNU Linux version 2.6.29.4
* GCC version 4.4.0 20090506 (Red Hat 4.4.0-4) (GCC)
**************************************** ****************************/
# Include <stdio. h>
# Include <stdlib. h>
# Include <malloc. h>
# Include <sys/types. h>
# Include <unistd. h>
Int
Main ()
{
Int frokret, fatherid;
If (frokret = fork ()))
{
Fatherid = getppid ();
Printf ("Father process is % d fatherid is % d \ n", frokret, fatherid );
Exit (0 );
}
Else if (frokret <0)
{
Printf ("fork is error \ n ");
}
Else
{
Frokret = getpid ();
Setsid ();
Fatherid = getppid ();
Printf ("Children getpid is % d fatherid is % d \ n", frokret, fatherid );
While (1)
{
// Printf ("this is children thread \ n ");
}
}
Exit (0 );
}
When the following is commented out: // setsid (); in this line, the running result is:
[Root @ UFO test] #./A. Out
Father process is 3229 fatherid is 3188
Children getpid is 3229 fatherid is 3228
[Root @ UFO test] # ps-Ef | grep A. Out
Root 3229 1 99 00:01:05 pts/3./A. Out
If setsid () is not commented out, the running result is:
[Root @ UFO test] #./A. Out
Father process is 3254 fatherid is 3188
Children getpid is 3254 fatherid is 3253
[Root @ UFO test] # ps-Ef | grep A. Out
Root 3254 1 99 09:05? 00:00:56./A. Out
Note PS-Ef | grep. the column after the column of the current time in the result after the out. When the setsid is commented out,. the parent process of out is pts/3, that is, the current terminal process, and does not implement a daemon function. If it is not commented out,. the parent process of out is? It indicates that its parent process is the INIT process, that is, process 1.