我正在编写自己的unix shell。当我尝试CTRL-C
这样的事情时,我的新子进程正在后台启动/运行。
但是当我在母进程(我的shell)中点击CTRL-C
时,它会关闭firefox(我的后台(-child)进程)。我不想用WIFEXITED(status)
关闭bg子进程。它应该什么都不做(它只应该杀死fg进程,如果除了我的shell之外还有其他东西)。
我已阅读void signal_handler(int signum) {
switch (signum) {
case SIGINT: // CTRL-C
cout << " [caught SIGINT]" << pid << endl;
if(pid != 0) {
kill(pid, SIGINT);
}
break;
case SIGTSTP: // CTRL-Z
cout << " [caught SIGTSTP]" << endl;
if(pid != 0) {
kill(pid, SIGTSTP);
}
break;
case SIGCHLD:
while((waitpid(pid,0, WNOHANG | WUNTRACED))>0) {
cout << "[" << pid << "] done" << endl;
}
break;
default:
break;
}
return;
}
,但我真的不知道如何使用它。
我的信号处理程序:
// some names of variables were changed to show it to you more readable.
signal(SIGINT, signal_handler);
signal(SIGTSTP, signal_handler);
signal(SIGCHLD, signal_handler);
if (input == "fg" || input == "bg") {
if (input == "fg") {
pid = inputPid(input); //function to get pid when user types something like fg 1234 (foreground pid 1234)
kill(pid, SIGCONT); // SIGCONT -> continue
cout << "[" << inputPid(input) << "]" << endl;
waitpid(pid, &status, WUNTRACED); // WUNTRACED -> return if a child has stopped
pid = 0;
} else if (input == "bg") {
bgPids.push_back(pid);
kill(pid,SIGCONT);
}
} else if(input == "background") {
cout << "PIDs in Background: ";
for(int i = 0; i < bgPids.size(); i++) { // vector which gets all background pids
cout << "[" << bgPids[i] << "] ";
}
cout << endl;
} else {
if ((pid = fork()) < 0) {
cout << "Error" << endl;
exit(1);
} else if (pid == 0) { // child
signal(SIGINT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
setpgid(0, getpid());
execvp(arguments[0], &arguments[0]);
cout << "Error" << endl;
exit(1);
} else if (checkIfBackground(inputNew) == false) { // mother
pid_t pid_r;
if (waitpid(pid, &status, WUNTRACED) < 0) {
cout << "Error" << endl;
}
} else { // when user types argument& or argument &
bgPids.push_back(pid);
cout << "Prozess is in background!" << endl;
if(WIFEXITED(status)) {
cout << "bg exited" << status << endl;
}
}
}
}
这就是我开始一个过程的方式:
FILE*