#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()的函数;在子过程中,可以在子过程中收到客户的数据,而我在父母过程中没有做任何事情(只是我正在退出)。后来致电守护程序在后台运行我的计时器任务
我的问题:如果我像上述一样执行,那么我的计时器任务将继续在后台运行,创建套接字将继续从客户端收回数据
守护程序的最简单方法是使用守护程序(3)库函数(内部基于fork
和setsid
...)附近的程序开头(例如,在创建任何内容之前线程)。
如果您的应用是这些类型之一:
{
".sh": "bash",
".py": "python",
".rb": "ruby",
".coffee" : "coffee",
".php": "php",
".pl" : "perl",
".js" : "node"
}
您想使用NPM的PM2软件包。
仅通过运行PM2启动就可以避免您的应用程序。
此外,虽然您的应用程序通常在1个核心上运行,但使用PM2,您可以在 All 内核上运行应用程序,并且将在内核之间加载平衡。如果这听起来对您来说太异国情调了,那么也很容易加载平衡!
这就是您要做的:
npm install -g pm2
pm2 start app.js -i 0 --name "api" # load balance app on all cores
pm2 start app.js --name "api" # run on 1 core, like apps typically do
然后:
pm2 startup (creates a pm2 systemd or equivalent service)
pm2 save (remembers the apps pm2 is running and starts them on reboot)
完成!