天天看點

Linux程序實踐(5) --守護程序

   守護程序是在需要在背景長期運作不受終端控制的程序,通常情況下守護程序在系統啟動時自動運作,在伺服器關閉的時候自動關閉;守護程序的名稱通常以d結尾,比如sshd、xinetd、crond、atd等。

   調用umask将檔案模式建立屏蔽字設定為一個已知值(通常是0)

   調用fork(),建立新程序,它會是将來的守護程序

   然後使父程序exit,保證子程序不是程序組組長

   調用setsid建立新的會話

      會話:是一個或者多個程序組的集合,通常一個會話開始與使用者登入,終止于使用者退出。在此期間,該使用者運作的所有程序都屬于這個會話期。

   将程序的目前目錄改為根目錄 (如果把目前目錄作為守護程序的目錄,目前目錄不能被解除安裝,它作為守護程序的工作目錄了。)

   關閉不再需要的檔案描述符

   将标準輸入、标準輸出、标準錯誤重定向到/dev/null

 setsid() creates a new session if the calling process is not a process group leader.  The calling process is the leader of the new session, the process group  leader  of  the  new process  group,  and has no controlling terminal.  The process group ID and session ID of the calling process are set to the PID of the calling process.  The calling process  will be the only process in this new process group and in this new session.

/*當調用程序不是一個程序組的組長時,Setsid建立一個新的會話;調用者程序會是這個會話期唯一的一個程序,且是該程序組的組長;調用者程序id是組id,也是會話期的id。不能用程序組組長去調用setsid函數*/

RETURN VALUE

       On  success,  the  (new)  session  ID  of  the  calling  process  is returned.  On error, (pid_t) -1 is returned, and errno is set to indicate the error.

參數:

   nochdir:=0将目前目錄更改至“/”

   noclose:=0将标準輸入、标準輸出、标準錯誤重定向至“/dev/null”

DESCRIPTION

       The  daemon()  function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons. If nochdir is zero, daemon() changes the calling process's current working  directory  to the root directory ("/"); otherwise, the current working directory is left unchanged. If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors.

Linux程式實踐(5) --守護程式

繼續閱讀