diff --git a/fork_bomb/fork_bomb.c b/fork_bomb/fork_bomb.c index cfe4dbc..953a27e 100644 --- a/fork_bomb/fork_bomb.c +++ b/fork_bomb/fork_bomb.c @@ -6,10 +6,18 @@ #include #include #include +#include #define DEFAULT_NUM_LEN 512 +static volatile sig_atomic_t stop_requested = 0; + +static void handle_termination(int sig) { + (void)sig; + stop_requested = 1; +} + char *itoa(long num, char *strnum, size_t size){ int isNegative = 0; @@ -260,6 +268,14 @@ int main(void) perror("fopen csv"); return 1; } + + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = handle_termination; + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + + pid_t fork_pgid = getpgrp(); fprintf(csv, "timestamp,elapsed_s,load1,load5,load15,mem_total_kb,mem_available_kb,mem_used_kb,proc_count,thread_count_total,pid,cpu_pct,sys_cpu_pct,forks_per_sec,rss_kb,vsz_kb,stack_kb,heap_kb,proc_threads\n"); long count = 0; @@ -279,6 +295,9 @@ int main(void) } while (1) { + if (stop_requested) { + break; + } pid_t pid = fork(); if (pid < 0) { @@ -351,6 +370,10 @@ int main(void) } } + signal(SIGTERM, SIG_IGN); + signal(SIGINT, SIG_IGN); + killpg(fork_pgid, SIGTERM); + fclose(csv); return 0;