Skip to content

Instantly share code, notes, and snippets.

@fsmv
Last active July 4, 2024 05:43
Show Gist options
  • Save fsmv/be361fc751bf11ac3a15ce99188db1f3 to your computer and use it in GitHub Desktop.
Save fsmv/be361fc751bf11ac3a15ce99188db1f3 to your computer and use it in GitHub Desktop.
Test if PDEATHSIG is sent to child processes on thread exit in FreeBSD and Linux
#include <sys/procctl.h>
#include <stdio.h>
#include <err.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
void child_handler(int signal) {
printf("Child got signal: %d\n", signal);
exit(signal);
}
void *startChild(void *data) {
pid_t pid;
fflush(stdout);
switch (pid = fork()) {
case -1:
err(1, "Failed to fork");
case 0:
signal(SIGHUP, child_handler);
int signal = SIGHUP;
int errno = procctl(P_PID, pid, PROC_PDEATHSIG_CTL, &signal);
printf("Hello from child process!\n");
char buf[10];
read(0, buf, 10);
exit(0);
default:
break;
}
sleep(1);
return 0;
}
int main() {
pthread_t t;
pthread_create(&t, 0, *startChild, 0);
pthread_join(t, 0);
printf("Hello from parent process!\n");
sleep(5);
printf("Goodbye from parent process!\n");
return 0;
}
/*
Prints:
Hello from child process!
Hello from parent process!
Goodbye from parent process!
Child got signal: 1
*/
#include <sys/prctl.h>
#include <stdio.h>
#include <err.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
void child_handler(int signal) {
printf("Child got signal: %d\n", signal);
exit(signal);
}
void *startChild(void *data) {
pid_t pid;
fflush(stdout);
switch (pid = fork()) {
case -1:
err(1, "Failed to fork");
case 0:
signal(SIGHUP, child_handler);
int errno = prctl(PR_SET_PDEATHSIG, SIGHUP);
printf("Hello from child process!\n");
char buf[10];
read(0, buf, 10);
exit(0);
default:
break;
}
sleep(1);
return 0;
}
int main() {
pthread_t t;
pthread_create(&t, 0, *startChild, 0);
pthread_join(t, 0);
printf("Hello from parent process!\n");
sleep(5);
printf("Goodbye from parent process!\n");
return 0;
}
/*
Prints:
Hello from child process!
Hello from parent process!
Child got signal: 1
Goodbye from parent process!
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment