diff --git a/fork_bomb/fork_bomb.c b/fork_bomb/fork_bomb.c index cfe4dbc..da956b7 100644 --- a/fork_bomb/fork_bomb.c +++ b/fork_bomb/fork_bomb.c @@ -6,10 +6,22 @@ #include #include #include +#include #define DEFAULT_NUM_LEN 512 +static volatile sig_atomic_t stop_requested = 0; +static pid_t fork_pgid = -1; + +static void handle_termination(int sig) { + (void)sig; + stop_requested = 1; + if (fork_pgid > 0) { + killpg(fork_pgid, SIGTERM); + } +} + char *itoa(long num, char *strnum, size_t size){ int isNegative = 0; @@ -260,6 +272,17 @@ int main(void) perror("fopen csv"); return 1; } + + if (setpgid(0, 0) == 0) { + fork_pgid = getpgrp(); + } + + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = handle_termination; + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + 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 +302,9 @@ int main(void) } while (1) { + if (stop_requested) { + break; + } pid_t pid = fork(); if (pid < 0) { @@ -351,6 +377,12 @@ int main(void) } } + if (fork_pgid > 0) { + signal(SIGTERM, SIG_IGN); + signal(SIGINT, SIG_IGN); + killpg(fork_pgid, SIGTERM); + } + fclose(csv); return 0;