【发布时间】:2011-02-05 06:02:50
【问题描述】:
我目前正在为我的某个项目编写一个多进程客户端和一个多线程服务器。
服务器是一个守护进程。 为了实现这一点,我正在使用以下 daemonize() 代码:
static void daemonize(void)
{
pid_t pid, sid;
/* already a daemon */
if ( getppid() == 1 ) return;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* At this point we are executing as the child process */
/* Change the file mode mask */
umask(0);
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
exit(EXIT_FAILURE);
}
/* Change the current working directory. This prevents the current
directory from being locked; hence not being able to remove it. */
if ((chdir("/")) < 0) {
exit(EXIT_FAILURE);
}
/* Redirect standard files to /dev/null */
freopen( "/dev/null", "r", stdin);
freopen( "/dev/null", "w", stdout);
freopen( "/dev/null", "w", stderr);
}
int main( int argc, char *argv[] ) {
daemonize();
/* Now we are a daemon -- do the work for which we were paid */
return 0;
}
在 Debian (Ubuntu) 上测试服务器时,我有一个奇怪的副作用。
accept()函数总是无法接受连接,返回的pid是-1
我不知道是什么原因造成的,因为在 RedHat 和 CentOS 中它运行良好。
当我删除对 daemonize() 的调用时,Debian 上一切正常,当我重新添加它时,同样的 accept() 错误重现。
我一直在监控 /proc//fd,一切看起来都不错。
daemonize() 和 Debian 发行版中的某些内容似乎不起作用。 (Debian GNU/Linux 5.0,Linux 2.6.26-2-286 #1 SMP)
知道是什么原因造成的吗?
谢谢
【问题讨论】:
-
在您的应用程序上运行 strace -f ,并包括从启动到第一个 accept() 失败的所有内容,希望这将包含一些线索。
-
打印/记录
errno的值可能有助于更好地确定accept(2)返回-1 的原因。
标签: c linux sockets posix daemon