我的一个项目遇到了问题, 我正在用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秒后发生