【问题标题】:Calling Linux Service with parameters使用参数调用 Linux 服务
【发布时间】:2012-12-30 20:23:36
【问题描述】:

我的 Linux 操作系统中有一个守护程序,我想在守护程序运行时从另一个 C 文件(该文件是守护程序控制器)向该守护程序传递参数。

我用谷歌搜索它,但直到现在我手里什么都没有。你能提供一些技巧吗?可以作为一个例子吗?

我的守护进程是从这个网站复制/粘贴:http://www.enderunix.org/docs/eng/daemon.php

/*
UNIX Daemon Server Programming Sample Program
Levent Karakas <levent at mektup dot at> May 2001

To compile: cc -o exampled examped.c
To run:     ./exampled
To test daemon: ps -ef|grep exampled (or ps -aux on BSD systems)
To test log:    tail -f /tmp/exampled.log
To test signal: kill -HUP `cat /tmp/exampled.lock`
To terminate:   kill `cat /tmp/exampled.lock`
*/

#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

#define RUNNING_DIR "/tmp"
#define LOCK_FILE   "exampled.lock"
#define LOG_FILE    "exampled.log"

void log_message(filename,message)
char *filename;
char *message;
{
FILE *logfile;
    logfile=fopen(filename,"a");
    if(!logfile) return;
    fprintf(logfile,"%s\n",message);
    fclose(logfile);
}

void signal_handler(sig)
int sig;
{
    switch(sig) {
    case SIGHUP:
        log_message(LOG_FILE,"hangup signal catched");
        break;
    case SIGTERM:
        log_message(LOG_FILE,"terminate signal catched");
        exit(0);
        break;
    }
}

void daemonize()
{
int i,lfp;
char str[10];
    if(getppid()==1) return; /* already a daemon */
    i=fork();
    if (i<0) exit(1); /* fork error */
    if (i>0) exit(0); /* parent exits */
    /* child (daemon) continues */
    setsid(); /* obtain a new process group */
    for (i=getdtablesize();i>=0;--i) close(i); /* close all descriptors */
    i=open("/dev/null",O_RDWR); dup(i); dup(i); /* handle standart I/O */
    umask(027); /* set newly created file permissions */
    chdir(RUNNING_DIR); /* change running directory */
    lfp=open(LOCK_FILE,O_RDWR|O_CREAT,0640);
    if (lfp<0) exit(1); /* can not open */
    if (lockf(lfp,F_TLOCK,0)<0) exit(0); /* can not lock */
    /* first instance continues */
    sprintf(str,"%d\n",getpid());
    write(lfp,str,strlen(str)); /* record pid to lockfile */
    signal(SIGCHLD,SIG_IGN); /* ignore child */
    signal(SIGTSTP,SIG_IGN); /* ignore tty signals */
    signal(SIGTTOU,SIG_IGN);
    signal(SIGTTIN,SIG_IGN);
    signal(SIGHUP,signal_handler); /* catch hangup signal */
    signal(SIGTERM,signal_handler); /* catch kill signal */
}

main()
{
    daemonize();
    while(1) sleep(1); /* run */
}

/* EOF */

【问题讨论】:

标签: c linux service daemon


【解决方案1】:

您没有明确说明控制器是相关进程(从共同的父进程开始)还是不相关的进程。如果它是相关的,你可以安排在控制器和守护进程之间有一个管道;如果没有,您可以使用 Unix 域套接字(参见 manpage unix(7))或 FIFO(mknod filename p)。无论哪种方式,将“睡眠”调用替换为包含“选择”或“轮询”调用的块,在控制流和任何其他感兴趣的文件或套接字上查找数据,如果数据可用,请读取它,解析它,然后采取行动。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多