gpt4 book ai didi

c++ - Linux (C++) 中的 fork 和等待。

转载 作者:太空宇宙 更新时间:2023-11-04 12:27:50 25 4
gpt4 key购买 nike

我想 fork 一个进程,然后在父进程中执行以下操作:

  1. 等到它自然终止或父设置的超时期限到期(类似于 Windows 中的 waitforsingalobject),之后我将使用 kill(pid) 终止进程;

  2. 获取子进程的退出码(假设自然退出)

  3. 我需要从父进程访问子进程的 std::cout。

我尝试使用 waitpid() 但是,虽然这允许我访问返回代码,但我无法使用此函数实现超时。

我还查看了以下解决方案 ( https://www.linuxprogrammingblog.com/code-examples/signal-waiting-sigtimedwait ),它允许我实现超时,但似乎没有办法获取返回码。

我想我的问题归结为,在 Linux 中实现这个的正确方法是什么?

最佳答案

您可以使用sigtimedwait 函数执行#1 和#2,使用pipe 执行#3:

#include <unistd.h>
#include <signal.h>
#include <iostream>

int main() {
// Block SIGCHLD, so that it only gets delivered while in sigtimedwait.
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGCHLD);
sigprocmask(SIG_BLOCK, &sigset, nullptr);

// Make a pipe to communicate with the child process.
int child_stdout[2];
if(pipe(child_stdout))
abort();

std::cout.flush();
std::cerr.flush();
auto child_pid = fork();
if(-1 == child_pid)
abort();

if(!child_pid) { // In the child process.
dup2(child_stdout[1], STDOUT_FILENO); // Redirect stdout into the pipe.
std::cout << "Hello from the child process.\n";
std::cout.flush();
sleep(3);
_exit(3);
}

// In the parent process.
dup2(child_stdout[0], STDIN_FILENO); // Redirect stdin to stdout of the child.
std::string line;
getline(std::cin, line);
std::cout << "Child says: " << line << '\n';

// Wait for the child to terminate or timeout.
timespec timeout = {1, 0};
siginfo_t info;
auto signo = sigtimedwait(&sigset, &info, &timeout);
if(-1 == signo) {
if(EAGAIN == errno) { // Timed out.
std::cout << "Killing child.\n";
kill(child_pid, SIGTERM);
}
else
abort();
}
else { // The child has terminated.
std::cout << "Child process terminated with code " << info.si_status << ".\n";
}
}

输出:

Child says: Hello from the child process.
Killing child.

如果sleep被注释掉:

Child says: Hello from the child process.
Child process terminated with code 3.

关于c++ - Linux (C++) 中的 fork 和等待。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44136064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com