首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C语言的后台编程

问C语言的后台编程
EN

Stack Overflow用户
提问于 2015-05-25 22:46:44
回答 2查看 347关注 0票数 0

我试图创建一个后台程序,其中包含另一个配置文件位置的主配置文件,并执行每个配置文件。例如:如果main_config.conf:

代码语言:javascript
复制
/home/conf1
/home/conf2

我想在后台执行./background_pro /home/conf1和./background_pro /home/conf2。我该怎么做?我在用structure.Thank下面的你

代码语言:javascript
复制
#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);
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-26 04:19:31

只需在shell命令的后面附加一个'&‘,该命令就会在后台运行。我想,这可能就是你想要的: daemon.bash

代码语言:javascript
复制
#!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

追捕恶魔:

代码语言:javascript
复制
nohup ./daemon.bash &

即使关闭终端,nohup也会使程序继续运行。

停止子进程1:

代码语言:javascript
复制
./daemon.bash -stop sub1
票数 1
EN

Stack Overflow用户

发布于 2015-05-26 04:31:05

后台程序可能是linux用户所称的"Daemon“程序。请在这里查看Creating a daemon in Linux,在这里您可以找到关于如何开始编写您自己的守护进程的大量信息。对于解析命令行参数,我建议阅读GNU库手册中的getopt()。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30446964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档