/*********************************************************************
* 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);
}
當注釋掉://setsid();這行的時候 運行結果為:
[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 09:03 pts/3 00:01:05 ./a.out
不注釋掉setsid();行的時候運行結果為:
[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
注意看 ps -ef | grep a.out後的結果中的目前時間的列後的那一列,當注釋掉setsid的時候a.out的父進程為pts/3,也就是當前所開的終端進程,並沒有實現一個守護進程的功能,而當不注釋掉的時候,a.out的父進程為?號,即表示它的父進程為init進程,也就是1號進程。