我试图创建一个后台程序,其中包含另一个配置文件位置的主配置文件,并执行每个配置文件。例如:如果main_config.conf:
/home/conf1
/home/conf2我想在后台执行./background_pro /home/conf1和./background_pro /home/conf2。我该怎么做?我在用structure.Thank下面的你
#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) {
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);
/* 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 ... */
sleep(30); /* wait 30 seconds */
}
exit(EXIT_SUCCESS);
}发布于 2015-05-26 04:19:31
只需在shell命令的后面附加一个'&‘,该命令就会在后台运行。我想,这可能就是你想要的: daemon.bash
#!bash
# to stop a sub process
if [ "x$1" = "x-stop" ]; then
if [ "x$2" = "xsub1" ]; then
kill `cat sub1.pid`
elif [ "x$2" = "xsub2" ]; then
kill `cat sub2.pid`
fi
exit
fi
# to start sub processes
conf1=`head -1 main_config.conf`
conf2=`head -2 main_config.conf | tail -1`
nohup ./background_pro $conf1 &
pid1=$!
echo "$pid1" > sub1.pid
nohup ./background_pro $conf2 &
pid2=$!
echo "$pid2" > sub2.pid追捕恶魔:
nohup ./daemon.bash &即使关闭终端,nohup也会使程序继续运行。
停止子进程1:
./daemon.bash -stop sub1发布于 2015-05-26 04:31:05
后台程序可能是linux用户所称的"Daemon“程序。请在这里查看Creating a daemon in Linux,在这里您可以找到关于如何开始编写您自己的守护进程的大量信息。对于解析命令行参数,我建议阅读GNU库手册中的getopt()。
https://stackoverflow.com/questions/30446964
复制相似问题