I am a c++ beginner. In our exercise we got a implement a shell, which creates childprocesses with fork() to handle commands. I tried to override SIGINT (strg+c) to kill all the childprocesses, in case they are running, and kill the parent only if no child process is running. But it seems that I can't override strg+c at all. It will always stop the whole program.
The main:
list<pid_t> PIDs;
int main() {
pid_t p;
pid_t tc;
signal(SIGINT, signal_handler);
atexit(killChildren);
for (;;) {
struct command cmd = read_command_line();
cout << "command: " << cmd.argv[0]
<< ", background: " << (cmd.background ? "ja" : "nein") << endl;
p = fork();
if (p == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (p == 0) {
execv(run(cmd).c_str(), cmd.argv);
} else {
PIDs.push_back(p);
if (cmd.background != 1) {
tc = wait(0);
PIDs.remove(p);
} else {
signal(SIGCHLD, signal_handler);
}
}
}
return 0;
}
the signal_handler:
void signal_handler(int signum) {
pid_t terminated_child;
switch (signum) {
case SIGINT:
printf("Caught signal %d\n",signum);
//Terminiert das Programm
if (!PIDs.empty()) {
signal(signum, SIG_IGN);
killChildren();
} else {
exit(signum);
}
break;
...
killChildren:
void killChildren (void) {
list<pid_t>::iterator it;
for (it = PIDs.begin(); it != PIDs.end(); it++) {
kill((*it), SIGTERM);
PIDs.remove((*it));
}
}
Example output:
ti2sh$ ping google.de &
command: ping, background: ja
PING google.de (173.194.35.159) 56(84) bytes of data.
64 bytes from google.de (173.194.35.159): icmp_req=1 ttl=53 time=30.2 ms
^C
--- google.de ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
Caught signal 2
rtt min/avg/max/mdev = 30.286/30.286/30.286/0.000 ms
Speicherzugriffsfehler (Speicherabzug geschrieben)
Like you can see, the printf is called, so I really don't understand why it stops the whole program after. Please help and thank you for reading!