首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从C++暂停和恢复外壳进程

从C++暂停和恢复外壳进程
EN

Stack Overflow用户
提问于 2021-10-08 14:26:05
回答 1查看 61关注 0票数 1

在C++中,我希望提交一个进程,暂停、恢复和停止它。为此,我首先使用以下函数在后台运行shell进程并保存关联的PID。我在this post找到了这个函数(只删除了标准输入和输出)。

代码语言:javascript
运行
复制
int system2(const char * command)
{
    int p_stdin[2];
    int p_stdout[2];
    int pid;

    if (pipe(p_stdin) == -1)
        return -1;

    if (pipe(p_stdout) == -1) {
        close(p_stdin[0]);
        close(p_stdin[1]);
        return -1;
    }

    pid = fork();

    if (pid < 0) {
        close(p_stdin[0]);
        close(p_stdin[1]);
        close(p_stdout[0]);
        close(p_stdout[1]);
        return pid;
    } else if (pid == 0) {
        close(p_stdin[1]);
        dup2(p_stdin[0], 0);
        close(p_stdout[0]);
        dup2(p_stdout[1], 1);
        dup2(::open("/dev/null", O_RDONLY), 2);
        /// Close all other descriptors for the safety sake.
        for (int i = 3; i < 4096; ++i)
            ::close(i);

        setsid();
        execl("/bin/sh", "sh", "-c", command, NULL);
        _exit(1);
    }

    close(p_stdin[0]);
    close(p_stdout[1]);

    
    return pid;
}

然后,我使用kill函数来暂停、恢复和停止这个过程,但它不能像我预期的那样工作。下面是一个示例:

代码语言:javascript
运行
复制
int main()
{
    // The process prints on file allowing me to figure out whether the process is paused / stopped, or is running
    const char * command = "for i in {1..1000}; do echo $i >> /Users/remi/test/data.txt; sleep 1s;done";

    // Run the command and record pid
    auto pid = system2(command);
    std::cout << "pid = " << pid << "\n";  
    // with this pid, I could ensure that `ps -p <pid>` returns the correct command

    std::cout << "process should be running!\n"; // It is!

    // wait
    std::this_thread::sleep_for(std::chrono::seconds(10));

    // pause
    kill(pid, SIGTSTP);
    std::cout << "process should be paused!\n"; // But it is not!

    // wait
    std::this_thread::sleep_for(std::chrono::seconds(10));

    // resume process
    kill(pid, SIGCONT);
    std::cout << "process should be running!\n"; // Sure, it is as it has never been stopped

    // wait 
    std::this_thread::sleep_for(std::chrono::seconds(10));

    // Kill process
    kill(pid, SIGSTOP);
    std::cout << "process should be stopped!\n"; // That worked!

    // wait 
    std::this_thread::sleep_for(std::chrono::seconds(10));
}

你能帮我弄清楚如何修复这个代码,以确保进程停止并恢复到我预期的状态吗?

仅供参考,我在macOS上,希望这个解决方案能在任何POSIX系统上工作。

EN

Stack Overflow用户

回答已采纳

发布于 2021-10-08 15:06:29

请注意,SIGTSTPSIGSTOP信号实际上都暂停了该过程。前者可以被进程忽略,但后者不能被忽略。如果您希望无论如何都暂停该过程,请使用SIGSTOP

要终止该进程,请使用SIGTERMSIGKILL

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69497468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档