我在C++中为linux创建了一个守护进程,但是,子进程似乎没有做任何事情。一旦达到if(pid> 0)语句,一切似乎停止。 的Daemon.Start()的代码如下:Linux守护进程无法正常工作
//Process ID and Session ID
pid_t pid,sid;
//Fork off the Parent Process
pid = fork();
if(pid < 0)
exit(EXIT_FAILURE);
//If PID is good, then exit the Parent Process
if(pid > 0)
exit(EXIT_SUCCESS);
//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
if((chdir("/")) < 0)
{
//Log the failure
exit(EXIT_FAILURE);
}
//Close out the standard file descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
//The main loop.
Globals::LogError("Service started.");
while(true)
{
//The Service task
Globals::LogError("Service working.");
if(!SystemConfiguration::IsFirstRun() && !SystemConfiguration::GetMediaUpdateReady())
{
SyncServer();
}
sleep(SystemConfiguration::GetServerConnectionFrequency()); //Wait 30 seconds
}
exit(EXIT_SUCCESS);
任何帮助将是巨大的! :)
使用库或脚本来做这种事情,不需要重新发明这个轮子。 – 2014-10-10 09:44:15
只需在stderr上放一个fprintf来发现子进程退出的位置。 – Claudio 2014-10-10 09:48:43