我一直在编写一个 linux 守护程序,它在 TCP/IP 上侦听请求并在接收到该请求时启动应用程序。我的问题是当我从命令提示符或 IDE (eclipse 3.7) 运行此守护程序时,一切正常并且我的可执行文件启动。但是当我使用
sudo service <myservicename> start
它时,它将在套接字上接收请求,但它不会启动该可执行文件。
这是我用于守护进程的标准代码 /// Linux 守护进程相关的东西
/// Create the lock file as the current user
int lfp = open( "/var/lock/subsys/LauncherService", O_RDWR|O_CREAT, 0640);
if ( lfp < 0 )
{
LOG_ERROR ("Unable to open lockfile");
LOG_ERROR ( strerror(errno) );
}
/// All
/// Our process ID and Session ID
pid_t pid, sid;
/// 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);
}
/// Change the file mode mask
umask(0);
/// Create a new SID for the child process
sid = setsid();
if (sid < 0)
{
LOG_ERROR ("Error Setting sid");
exit(EXIT_FAILURE);
}
LOG_INFO ("sid set");
/// Change the current working directory
if ( (chdir("/usr/local/<mylocaldir>/bin")) < 0 )
{
LOG_ERROR ("Error changing Directory");
exit(EXIT_FAILURE);
}
LOG_INFO ("chdir successful");
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
这是我启动需要启动的二进制文件的功能。这个函数在分叉的子进程中被调用。
std::string configFile = "/usr/local/<mydir>/config/Settings.config";
std::string binary = "<binaryname>";
std::string path ="/usr/local/<mydir>/bin/<binaryname>";
//char *argv[] = { "<binaryname>", "/usr/local/<mydir>/config/Settings.config", (char *)0 };
LOG_INFO("Calling Process" );
if ( execlp( path.c_str(), binary.c_str(), configFile.c_str(), (char *)0 ) == -1 )
//if ( execv("/usr/local/<mydir>/bin/<binaryname>", argv) == -1 )
//if ( execvp("/usr/local/<mydir>/bin/<binaryname>", argv) == -1 )
{
LOG_ERROR("System call failed !!")
std::string errString = strerror(errno);
LOG_ERROR (errString );
}
else
{
LOG_INFO("System call successful");
}