-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsignals.c
77 lines (63 loc) · 1.71 KB
/
signals.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "shell.h"
#include "utils.h"
#include "process.h"
#include "signals.h"
#include "prompt.h"
void init_signals() {
signal(SIGCHLD, child_dead);
signal(SIGTSTP, sigtstp_handler);
signal(SIGINT, sigint_handler);
}
void child_dead(int sig_num) {
// a child process terminated
// update process data structures and print an alert
int w_st;
pid_t pid = waitpid(-1, &w_st, WNOHANG);
if (pid <= 0) {
return;
}
// get the name of the dead process and remove it from the list
proc* p = get_data_by_pid(processes, pid);
char* pname;
if (p != NULL) {
char* temp = p->pname; // Don't free temp
pname = (char*)malloc(sizeof(char) * (strlen(temp) + 1));
strcpy(pname, temp);
processes = delete_node_by_pid(processes, pid);
} else {
pname = (char*)malloc(sizeof(char) * MAX_STATIC_STR_LEN);
strcpy(pname, "Process");
}
// print an alert
if (WIFEXITED(w_st) && WEXITSTATUS(w_st) == EXIT_SUCCESS) {
fprintf(stderr, ANSI_RED_BOLD "\nALERT: %s with ID %d exited normally.\n" ANSI_DEFAULT, pname, pid);
} else {
fprintf(stderr, ANSI_RED_BOLD "\nALERT: %s with ID %d exited abnormally.\n" ANSI_DEFAULT, pname, pid);
}
prompt();
fflush(stdout);
free(pname);
return;
}
void sigtstp_handler(int signum) {
pid_t pid = getpid();
if (pid != SHELL_PID) {
// CHILD PROCESS
return;
}
if (FG_CHILD_PID == -1) {
return;
}
raise(SIGTSTP);
}
void sigint_handler(int signum) {
pid_t pid = getpid();
if (pid != SHELL_PID){
// child process
return;
}
if (FG_CHILD_PID == -1) {
return;
}
raise(SIGINT);
}