how can i make my linux service trigger my signal?

时间:2015-06-30 13:32:45

标签: c++ linux service

I have made my first linux service with C++.

pid_t pid, sid;

pid = fork();
if (pid < 0) {
    exit(EXIT_FAILURE);
}
if (pid>0) {
    exit(EXIT_SUCCESS);
}

umask(0);

sid = setsid();
if (sid < 0) {
    exit(EXIT_FAILURE);
}

if ((chdir("/")) < 0) {
    exit(EXIT_FAILURE);
}

close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);

while (1) {
    ????????
    //sleep(10);
}

exit(EXIT_SUCCESS);

What it would do is to wait for my signal and when it receives it to do some tasks and then again wait for my next signal.

I would send my signal (or whatever) somehow from within my c++ app that runs on same machine. Seems like a mechanism of semaphore between two apps. But in this case one is a linux service, and I do not know how the service could wait my signal.

How could I achieve this? What are my alternatives?

Thanks.

Note: The word "signal" caused to confusion. I didn't intend to use that word as technically. I just mean that I need to talk to my linux service from within my cpp app.

NOTE 2: Using signal is not useful because in its handler almost doing any thing is unsafe, whereas I need to do lots of things. (I dont know if I could start a thread, at least!)

2 个答案:

答案 0 :(得分:1)

Here is an example of an handler that takes care of SIGHUP and SIGTERM, your program could send these signals using kill -9 processid or kill -HUP processid of course there is a few other signals you could use for this purpose check man signal

void handler (int signal_number){
    //action
    exit(1);
}

And in the main program

struct sigaction act;
struct sigaction act2;
memset (&act, 0, sizeof (act));
memset (&act2, 0, sizeof (act2));

act.sa_handler = handler;
act2.sa_handler = handler;
if (sigaction (SIGHUP, &act, NULL) < 0) {
    perror ("sigaction");
}

if (sigaction (SIGTERM, &act, NULL) < 0) {
    perror ("sigaction");
}

//wait here for ever or do something.

答案 1 :(得分:1)

最后,我找到了正确的关键词来谷歌我需要知道的。 以下是在不同流程之间进行通信的替代方法:

http://www.tldp.org/LDP/lpg/node7.html