Re: [問題] 請問寫成 daemon 的問題...
※ 引述《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
05/28 00:32, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
LinuxDev 近期熱門文章
PTT數位生活區 即時熱門文章