Skip to content

Instantly share code, notes, and snippets.

@sielaq
Created November 6, 2015 18:24
Show Gist options
  • Save sielaq/9867be2d1b65ffec658c to your computer and use it in GitHub Desktop.
Save sielaq/9867be2d1b65ffec658c to your computer and use it in GitHub Desktop.
Trap signal - helpful to debug
/*
gcc trap_signal.c -o trap_signal
start:
./trap_signal $(pidof trap_signal)
tail -f /tmp/log.txt
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdbool.h>
bool terminate = false;
int trap_signal = 0;
void sig_handler(int sig)
{
trap_signal = sig;
terminate = true;
}
int main(int argc, char *argv[])
{
if (signal(SIGUSR1, sig_handler) == SIG_ERR) printf("\ncan't catch SIGUSR1\n");
if (signal(SIGTERM, sig_handler) == SIG_ERR) printf("\ncan't catch SIGTERM\n");
if (signal(SIGHUP, sig_handler) == SIG_ERR) printf("\ncan't catch SIGHUP\n");
if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n");
int count;
if (argc > 1)
{
for (count = 1; count < argc; count++)
{
printf("pid = %i\n", atoi(argv[count]) );
kill( atoi(argv[count]),SIGTERM);
}
}
pid_t process_id = 0;
pid_t sid = 0;
process_id = fork();
if (process_id < 0) {
printf("fork failed!\n");
exit(1);
}
if (process_id > 0) {
printf("process_id of child process %d \n", process_id);
exit(0);
}
umask(0);
sid = setsid();
if (sid < 0) {
exit(1);
}
chdir("/tmp");
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
while (!terminate) {
sleep(1);
}
FILE *fp = NULL;
fp = fopen("log.txt", "a");
fprintf(fp, "received %i terminated...exiting\n", trap_signal);
fflush(fp);
fclose(fp);
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment