Search code examples
cprocesssignals

Stopping a daemon in C


My signal handler looks like:

volatile sig_atomic_t loop     = 1;

void handle()
{
    loop = 0;
}

And, I have a daemon which is like:

void _start_()
{
...
sa.sa_handler = handle;
sigaction(SIGINT, &sa, NULL);
while(loop)
{
   //add a line to a file
}
...
}

I want to stop the daemon, from another function like:

void _stop_()
{
    raise(SIGINT);
}

My idea is, somehow if the value of loop is 0, then the while would be evaluated as false, and the daemon exits. I am planning to use these two functions like:

_start_(); //daemon starts
//computation
_stop_() //daemon stops writing to the file. exits

How can I achieve this? The problem is I am not able to stop the daemon from _stop_().

Thanks


Solution

  • Is the _stop_() function called from a separate process from your daemon? If so, then it needs to know the ID of the process to signal. The normal practice is that the daemon writes its process ID to a file (a PID file) which can then be read by the process that stops the daemon.