Background daemon Creation

Source: Internet
Author: User
Tags syslog

Background daemon Creation

Damon.c



#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <signal.h>
#include <time.h>
#include <syslog.h>
Initializing the daemon daemon
int Init_diamon (void) {
int pid;//Process
int i;
Ignore terminal IO signal and stop signal
Signal (sigttou,sig_ign);
Signal (sigttin,sig_ign);
Signal (sigtstp,sig_ign);
Signal (sighup,sig_ign);
Creating a process
Pid=fork ();
if (pid>0) {
Exit (0);//End the parent process so that the child thread becomes a background process
}
else if (pid<0) {
return-1;
}


Setsid ()///////////////////////////////


To create a new child process again
Pid=fork ();
if (pid>0) {
Exit (0);
}
else if (pid<0) {
return-1;
}
Closes the inherited file descriptor
For (I=0;i<nofile;close (i++));


Change working directory so that it has no file system associated
ChDir ("/");


Set the file screen Word to 0
Umask (0);
Ignore signal
Signal (sigchld,sig_ign);


return 0;








}




int main (void) {


time_t now;
Init_diamon ();
Syslog (log_info| Log_user, "test daemon \ \ \");
while (1) {
Sleep (8);
Time (&now);
Syslog (log_info| Log_user, "System time: \t%s\t\n", CTime (&now));
}
}



Gcc-o Demon Demon.c

./demon


Verifying PS Aux|grep Demon

Tail-f/var/log/syslog
Aug 11:25:50 Server Demon: System time: #011Wed Aug ten 11:25:50 2016
Aug 11:25:58 SERVER Demon: System time: #011Wed Aug 11:25:58 2016
Aug 11:26:06 SERVER Demon: System time: #011Wed Aug 11:26:06 2016
Aug 10 11 : 26:14 SERVER Demon: System time: #011Wed Aug 11:26:14 2016
Aug 11:26:22 SERVER Demon: System time: #011Wed Aug 10 11:26:22 2016
Aug 11:26:30 SERVER Demon: System time: #011Wed Aug 11:26:30 2016

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.