在Debian上的Daemonize()问题

我目前正在为一些项目编写一个多进程客户端和一个multithreading服务器。

该服务器是一个守护进程。 为了做到这一点,我使用下面的守护进程()代码:

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)上testing服务器时,我有一个奇怪的副作用。

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)

任何想法是什么造成这个?

谢谢

accept(2)手册说:

EINVAL套接字不侦听连接,或者addrlen无效(例如,为负数)。

可能你有类似的东西

 struct sockaddr_in; socklen_t len; ... new_fd = new_fd = accept(sockfd,(struct sockaddr *)&addr,&len); 

但是,您需要将len设置为您传入的地址的大小:

 struct sockaddr_in addr; socklen_t len; len = sizeof(addr); ... new_fd = new_fd = accept(sockfd,(struct sockaddr *)&addr,&len); 

所以,通过一些(非)幸运的手段,你的未初始化的“len”变量在某些情况下会得到一些无意义的值,并且接受失败,而碰巧在其他情况下工作。

我可以指导你现有的库函数daemon(3)来完成相同的?

在这里,当父母退出时:

 /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } 

你应该调用_exit() ,而不是exit() 。 (我不确定这是否会导致您的问题,但是这是可能的)。

accept()返回-1时, errno是什么设置的? (你可以把一个perror("accept");在那里的代码)。