Skip to content

Instantly share code, notes, and snippets.

@jgehrcke
Created July 22, 2015 16:13
Show Gist options
  • Save jgehrcke/5e8ed47ed91ca0f7c2c6 to your computer and use it in GitHub Desktop.
Save jgehrcke/5e8ed47ed91ca0f7c2c6 to your computer and use it in GitHub Desktop.
A snippet for testing libev signal watcher behavior across fork and loop destruction.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <ev.h>
void sigtermhandler(struct ev_loop *l, ev_signal *w, int revents) {
printf("SIGTERM handler called in process %d\n", getpid());
ev_break(l, EVBREAK_ALL);
}
void child(struct ev_loop *loop) {
printf("Msg from child with PID %d\n", getpid());
ev_loop_destroy(loop);
// Reset signal handler:
//signal(SIGTERM, SIG_DFL);
struct ev_loop *newloop = ev_default_loop(0);
ev_run(newloop, 0);
}
int main (void) {
printf("Msg from parent with PID %d\n", getpid());
struct ev_loop *loop = EV_DEFAULT;
// Install signal watcher in parent, handling SIGTERM.
ev_signal signal_watcher;
ev_signal_init(&signal_watcher, sigtermhandler, SIGTERM);
ev_signal_start(loop, &signal_watcher);
pid_t pid;
pid = fork();
if (pid == -1) {
fprintf(stderr, "Can't fork, error %d\n", errno);
exit(1);
}
else if (pid == 0) {
child(loop);
exit(0);
}
// Dirtywait until child is upnrunning, then send SIGTER.
sleep(1);
kill(pid, SIGTERM);
//ev_run (loop, 0);
printf("Waiting for child.\n");
wait();
printf("Child finished, exit parent.\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment