如何恢复已停止的进程



根据本文档,我正在测试如何停止和恢复流程。我有如下基本代码要测试:

#include <iostream>
#include <csignal>
#include <unistd.h>
int main() {
std::cout << "Hello" << std::endl;
int pid = getpid();
kill(pid, SIGSTOP);
kill(pid, SIGCONT);
std::cout << "Bye" << std::endl;
return 0;
}

输出为:

Hello

它停止了进程,但从未恢复。我应该如何修复它?

一个解决方案,如果有点复杂的话,就是创建一个子进程来启动和停止父进程。这里有一个小代码示例,可能会有所帮助:

#include <iostream>
#include <csignal>
#include <unistd.h>
int pid; //Include declaration outside so it transfers to the child process
int main() {
std::cout << "Hello" << std::endl;
pid = getpid();
int returned_pid = fork(); //Duplicate process into 2 identical processes
if(returned_pid) {
// If it is the parent process, then fork returns the child process pid
// This is executed by the parent process
usleep(1000); // Sleep a millisecond to allow for the stop command to run
} else {
// If fork returns 0, then it is the child process
// The else is executed by the child process
kill(pid, SIGSTOP); // Stop parent process
usleep(3000000);    // Delay 3 seconds
kill(pid, SIGCONT); // Resume parent process
}
if(returned_pid) { // Only print if parent process
std::cout << "Bye" << std::endl;
}
return 0;
}

澄清:fork命令在两个进程中返回两个不同的值:子进程中的0和父进程中的子进程的pid。

其他注意事项:当在终端中运行此程序时,它看起来会很奇怪,因为终端可能会注意到进程已停止并给出一个新的命令行,但随后进程恢复,因此在其上打印Bye。只是一个注意事项。

最新更新