#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
int main(void) {
/* Our process ID and Session ID */
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid == 0) { //child process
CreateSocket(); //this function will recieve the data from the client
}
else
{
exit(EXIT_SUCCESS); //exit the parent process
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log the failure */
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);
/* Daemon-specific initialization goes here */
/* The Big Loop */
while (1) {
/* Do some task here ... */
Timer(); // this will create a timer and call the task for every 2ms, 10ms
}
exit(EXIT_SUCCESS);
}
我的任务是通过套接字从客户端接收数据并在后台运行计时器。所以我创建了一个父进程和子进程,后来又创建了守护进程在后台运行。我调用了名为 CreateSocket() 的函数;在子进程中从子进程中的客户端接收数据,而我在父进程中没有做任何事情(只是我正在退出)。稍后调用守护进程在后台运行我的定时器任务
我的问题:如果我像上面那样做,那么我的定时器任务将继续在后台运行,创建套接字将继续从客户端接收数据
最佳答案
守护进程的最简单方法是使用 daemon(3)程序开头附近的库函数(内部基于 fork
和 setsid
...)(例如,在创建任何线程之前)。
关于在 linux 中创建一个守护进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22280848/