简体   繁体   中英

how can i make my linux service trigger my signal?

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!)

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.

Finally I have found the right keywords to google what I needed to know. Here are the alternative ways to communicate between different processes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM