我的一个项目遇到了问题, 我正在用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;
}

使用Makfile

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秒后发生

推荐答案

当您restart_process时,您不会判断-1的结果值.因此,当Forking 的子元素返回时,它会像在主过程中一样继续,只是下次它杀死假定的子元素时,它会调用kill(-1, ...),从而杀死您有权杀死的所有东西.

不管怎样,差不多吧.

Linux相关问答推荐

Microsoft ODBC Driver 18 for Python Docker Image,ARM设备;生成错误

线程创建会在 Linux 中触发页面错误吗?它与软脏 PTE 有什么关系?

构建 python 映像时 Docker compose 问题,访问被拒绝或存储库不存在

如何删除文件中不需要的字符(使用 shell 脚本)

Linux time 命令输出中 real、user 和 sys 的含义

未定义的引用 'shm_open',已在此处添加 -lrt 标志

在 Ubuntu 中重启 Nginx

Linux 上 pid_t、uid_t、gid_t 的大小

如何在 Ubuntu 12.04 中更改 Jenkins 安装的端口号

让 Tk 看起来像一个原生 Linux 应用程序

pthread_exit 与返回

我可以在 Ubuntu 上使用 Homebrew 吗?

Pthread mutex互斥断言错误

如何知道是否有足够的内存可以在 Linux 机器上部署新应用程序?

如何在 Linux 中删除早于特定日期的文件?

ngrok 如何在防火墙后工作?

在linux上上几个目录

在不运行测试的情况下制作(从源代码安装)python

仅当文件存在于 shell 脚本中时才移动

将 BlueZ Stack 用作外设(广告商)