无法覆盖SIGINT(c ++)

时间:2013-11-17 15:50:19

标签: c++ process

我是一名c ++初学者。在我们的练习中,我们得到了一个实现shell,它使用fork()创建子进程来处理命令。 我试图覆盖SIGINT(strg + c)以杀死所有子进程,以防它们正在运行,并且仅在没有子进程运行时才终止父进程。但似乎我根本无法覆盖strg + c。它将永远停止整个程序。

主要:

    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;
}

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));             
    }
}

示例输出:

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)

就像你看到的那样,printf被调用了,所以我真的不明白为什么它会在之后停止整个程序。请帮助并感谢您的阅读!

0 个答案:

没有答案