Create a simple GNU daemon

Source: Internet
Author: User

/*************************************** ******************************
* 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.