Re: [問題] 請問寫成 daemon 的問題...

看板LinuxDev作者 (不要再推錯文了)時間18年前 (2007/05/09 20:35), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《KvsG (KvsG)》之銘言: : 我有一支 TCP Server 的小程式... : 大概長下面這樣... 它本身就是一個 TCP Server 的型態了... : 執行後就會進入無限迴圈... 然後就是接受 TCP connect 並回應... : int main() { : classObj O; : O.Start(); : } : 然後我想知道怎麼把它寫成 daemon... : 可以說我執行 ./daemon 後, 這程式就自已在背景跑... : 請問有什麼參考資料嗎 謝謝 A sample code to build a deamon process: /************************************************************************ * File Name : deamon.c ************************************************************************/ #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int deamon_init(void) { pid_t pid; if ( (pid = fork()) < 0) { /* * Create child process false */ return (-1); } else if (pid != 0) { /* * Parent goes bye-bye */ exit(0); } /* * Child continues */ setsid(); /* Become session leader */ chdir("/"); /* Change working directory */ umask(0); /* clear our file mode creation mask */ return (0); } int main(void) { if (-1 != deamon_init()) { while (1) { sleep(10); } } return (0); } ************************************************************************ * Compile Command: ************************************************************************ [root@localhost temp]# gcc -Wall deamon.c -o deamon ************************************************************************ * Result: ************************************************************************ [root@localhost temp]# ./deamon [root@localhost temp]# ps aux | grep deamon root 3123 0.0 0.0 1484 176 ? Ss 04:38 0:00 ./deamon root 3125 0.0 0.0 3888 672 pts/1 R+ 04:38 0:00 grep deamon [root@localhost temp]# ************************************************************************ * Reference: ************************************************************************ Advanced Programming in the UNIX Environment, ISBN 0-201-56317-7 Chapter 13 Deamon Processes W. Richard Stevens (UNIX大師) ************************************************************************ * PS: ************************************************************************ 這是這本書第一版的寫法,我想第二版的應該會有改寫:) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.70.77.219

05/09 23:40, , 1F
謝謝! 謝謝!! 惠我良多... 感恩啊~~~
05/09 23:40, 1F
※ 編輯: wlsabcd 來自: 203.70.77.219 (05/10 08:10)

05/28 00:32, , 2F
不知道會不會有下一版...Stevens 已故... T.T
05/28 00:32, 2F
文章代碼(AID): #16GS0SSQ (LinuxDev)
討論串 (同標題文章)
文章代碼(AID): #16GS0SSQ (LinuxDev)