this documentation之后,我正在测试如何停止和恢复一个进程.我有基本代码要测试,如下所示:

#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,父进程中的子进程的ID.

其他注意事项:当在终端中运行这段代码时,它看起来会很奇怪,因为终端可能会注意到该进程已停止并给出一个新的命令行,但随后该进程继续运行,因此在上面打印Bye.只是一张纸条.

Linux相关问答推荐

Bash脚本用于在远程工作后关闭用户会话

AddressSaniizer随机抛出没有任何解释的SIGSEGV

如何更正我的CMakeLists.txt,使我的项目同时构建在Linux和Windows上?

UTF-8输入和使用XGetICValues

为什么 liburing 写入性能低于预期?

erlang 格式的 utf8 变为 \x(反斜杠 x)ascii 编码

RabbitMQ 安装后没有自动启动

matlab中linux和windows上regexp()的不同行为

在android上使用lldb-server进行lldb调试?

std::system 使用什么Shell?

另一个远程的 Git 合并分支

判断指定名称的画面是否存在

如何在初始化脚本中以特定用户身份运行命令?

使用 AWS CLI 进行 Bash - 无法找到凭证

如何使用该位置的相对路径在单个位置创建多个文件夹?

Eclipse 的 C# 插件

什么是最有效的不区分大小写的 grep 用法?

yum 可以告诉我哪些存储库提供了特定的包吗?

/var 中有什么?

bash / Makefile中双美元符号的含义是什么?