Linux 下,如何建立守護程序

2021-06-13 13:49:37 字數 2704 閱讀 3791

最近在看apue,記錄一下如何建立乙個完整的守護程序。以備不時檢視。(注:redhat在/var/log/messages檔案中,可檢視syslog函式記錄的日誌。)

[cpp]view plain

copy

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#define lockfile "/var/run/daemon.pid"

#define lockmode (s_irusr | s_iwusr | s_irgrp | s_iroth)

void

daemonize(

const

char

*);  

void

my_err(

char

*);  

intlockfile(

int);  

intalready_running(

void

);  

void

reread(

void

);  

void

*thread_fn(

void

*);  

sigset_t mask;  

intmain(

intargc,

char

*argv)  

else

cmd++;  

//become a daemon

daemonize(cmd);  

//make sure only one copy of the daemon is running

if(already_running())  

//restore sighup default and block all signals.

sa.sa_handler=sig_dfl;  

sigemptyset(&sa.sa_mask);  

sa.sa_flags=0;  

if(sigaction(sighup,&sa,null)<0)  

sigfillset(&mask);   

if((err=pthread_sigmask(sig_block,&mask,null))<0)  

//create a thread to handle sighup and sigterm  

err=pthread_create(&tid,null,thread_fn,null);  

if(err<0)  

//proceed with the rest of daemon

sleep(100);  

printf("end\n"

);  

exit(0);  

}  //reread the configuration file

void

reread(

void

)    

void

*thread_fn(

void

*arg)  

switch

(signo)  

}  return

0;  

}  //whether a daemon process is already running

//running: return 1

//no run:return 0

intalready_running(

void

)    

if(lockfile(fd)<0)  

syslog(log_err,"can't lock %s:%s"

,lockfile,strerror(errno));  

return

1;  

}  ftruncate(fd,0);  

sprintf(buf,"%ld"

,(long

)getpid());  

write(fd,buf,strlen(buf));  

return

0;  

}  //lock the whole file pointed by fd

intlockfile(

intfd)  

//make a process to a daemon.

void

daemonize(

const

char

*cmd)  

//attach file descriptors 0,1,and 2 to /dev/null

fd0=open("/dev/null"

,o_rdwr);  

fd1=dup(0);  

fd2=dup(0);  

//initialize the log file

openlog(cmd,log_cons,log_daemon);  

if(fd0!=0 || fd1!=1 || fd2!=2)  

}  void

my_err(

char

*str)  

Linux 守護程序建立

守護程序是在後台執行,不受使用者的控制 守護程序沒有任何存在的父程序。如果乙個程序想成為守護程序,有fork 建立 然後終止父程序,脫離資源。例子 void init daemon int pid,i pid fork if pid exit 0 結束父程序 else exit 1 失敗退出 是子程...

linux下建立後台守護程序例項

步驟 1.父程序通過fork函式建立乙個子程序,然後父程序退出 2.子程序中使用setsid函式建立乙個新的會話 3.切換程序的工作目錄到根目錄 4.設定程序的umask為0 5.關閉不需要的檔案操作符 例項 include incude include include include includ...

linux 守護程序詳解及建立守護程序

linux 守護程序詳解及建立守護程序 守護程序是一種後台執行並且獨立於所有終端控制之外的程序。守護程序的啟動 要啟動乙個守護程序,可以採取一下幾種方式 守護程序的建立 先來看乙個守護程序建立的例子 include include include include define maxfd 64 vo...