一种解决方案是创建子进程来启动和停止父进程,尽管有点复杂.下面是一个小代码示例,它可能会有所帮助:
#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,父进程中的子进程的ID.
其他注意事项:当在终端中运行这段代码时,它看起来会很奇怪,因为终端可能会注意到该进程已停止并给出一个新的命令行,但随后该进程继续运行,因此在上面打印Bye
.只是一张纸条.