The application is multi-threaded.
Inside main()
, I register the signal handler for SIGUSR1:
// Global variable to indicate whether directory's
// content needs to be reloaded
bool reload_dir = 0;
int main (int argc, char *argv[])
{
...
signal(SIGUSR1, sigusr1_handler);
...
RunServer(arg1, ...);
return 0;
}
Signal handler:
static void
sigusr1_handler (int signo __unused)
{
reload_dir = 1;
return;
}
The following function (which is called from main) is only executed by the main thread:
void
RunServer (arg1, ...)
{
// do some stuffs
...
while (cond != true) {
sleep(1);
}
server_exit();
}
Now, when the SIGUSR1 is caught (by any thread including the main thread), I'm setting the reload_dir variable to 1. And in RunServer()
, I'm reloading the directory based on that value. However, I'm also resetting the global variable reload_dir
to 0 to avoid loading the directory repeatedly indefinitely. And this setting reload_dir
to 0 will introduce a race.
Since we should not use locks or mutex in a signal handler, how can I achieve this without majorly changing the existing application design.
void
RunServer (arg1, ...)
{
// do some stuffs
...
while (cond != true) {
if (reload_dir) {
// reset reload_dir to avoid loading repeatedly indefinitely
reload_dir = 0; // Race condition?
dir_reinit();
}
sleep(1);
}
server_exit();
}