C++ Kill() 使 linux 崩溃到登录屏幕

问题描述 投票:0回答:1

我的一个项目遇到问题, 我正在使用 fork 创建子进程,然后使用 Kill(pid,SIGINT) 终止它们,然后重新启动它们 第二次中断进程后,linux 将崩溃到登录屏幕。所以也有可能 gnome 或我的窗口管理器实际上是崩溃的原因 我不知道如何解决这个问题。 这是导致崩溃的代码

#include <iostream>
#include <signal.h>
#include <thread>

const int CHILDREN = 3;
bool is_active;

using namespace std;

void signalHandler(int signum)
{
    cout << "Interrupt signal (" << signum << ") received.\n";

    // cleanup and close up stuff here
    // terminate program

    is_active = false;
}

pid_t fork_process(int process_nr)
{
    pid_t c_pid;
    c_pid = fork();
    if (c_pid == -1)
    {
        perror("failure to fork new process");
        return -1;
    }
    else if (c_pid == 0)
    { // child process
        signal(SIGINT, signalHandler);
        is_active = true;
        while (is_active)
        {
        }
        cout << "child " << process_nr << " EXIT" << endl;
        return -1;
    }
    return c_pid;
}

pid_t restart_process(int process_nr, pid_t pid)
{
    cout << "restart process " << process_nr << endl;
    pid_t new_c_pid;
    kill(pid, SIGINT);//THIS IS WHERE THE CRASH HAPPENS

    sleep(3);

    new_c_pid = fork_process(process_nr);
    return new_c_pid;
}

int main(int argc, char const *argv[])
{
    int ret;
    pid_t c_pid[CHILDREN];

    for (int i = 0; i < CHILDREN; i++)
    {
        ret = fork_process(i);
        if (ret == -1)
            return 0;
        c_pid[i] = ret;
        cout << "parent created child " << i << " with c_pid " << c_pid[i] << endl;
    }

    int to_restart = 1;

    this_thread::sleep_for(chrono::seconds(16));

    // restart the selected process
    c_pid[to_restart] = restart_process(to_restart, c_pid[to_restart]);

    this_thread::sleep_for(chrono::seconds(16));

    // restart the selected process
    c_pid[to_restart] = restart_process(to_restart, c_pid[to_restart]);//THIS IS WHERE THE CRASH HAPPENS

    this_thread::sleep_for(chrono::seconds(16));
    return 0;
}

使用 Makefile

CC = g++
CFLAGS = -Wall -g

output: main.o
    $(CC) $(CFLAGS) -o output main.o
main.o: main.cpp
    $(CC) $(CFLAGS) -c  main.cpp
clean:
    rm *.o output

感谢您的帮助。

重新启动一次工作正常,所以我不知道调用它两次会如何导致崩溃 我已经用 gdb 运行它并标记了崩溃发生的位置。但是它不会立即发生,而是在执行kill()函数后5秒后发生

c++ linux crash fork kill
1个回答
0
投票

当您

restart_process
时,您并不是在检查
-1
的结果值。因此,当分叉的子进程返回时,它会像在主进程上一样继续运行,只是下次它杀死假定的子进程时,它会调用
kill(-1, ...)
来杀死您有权杀死的所有内容。

无论如何,类似的事情。

© www.soinside.com 2019 - 2024. All rights reserved.