gpt4 book ai didi

c++ - 创建 3 个子进程并在指定秒数后退出它们

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

输出应该是什么样子的图像:我的问题是我需要编写一个程序来接受 3 个进程的名称作为命令行参数。每个进程将运行如下秒数:(PID%10)*3+5 并终止。这 3 个子进程终止后,父进程将重新安排每个 child 。当所有子进程都被重新安排 3 次后,父进程将终止。我已经使用 fork 创建了三个 child ,但很难让他们按照特定标准退出?

using namespace std;

int main(){
int i;
int pid;
for(i=0;i<3;i++) // loop will run n times (n=3)
{
if(fork() == 0)
{
pid = getpid();
cout << "Process p" << i+1 << " pid:" << pid << " Started..." << endl;
exit(0);
}
}
for(int i=0;i<5;i++) // loop will run n times (n=3)
wait(NULL);

}

最佳答案

您可以使用sigtimedwait等待 SIGCHLD 或超时。

工作示例:

#include <cstdio>
#include <cstdlib>
#include <signal.h>
#include <unistd.h>

template<class... Args>
void start_child(unsigned max_runtime_sec, Args... args) {
// Block SIGCHLD.
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGCHLD);
sigprocmask(SIG_BLOCK, &set, nullptr);
// Enable SIGCHLD.
signal(SIGCHLD, [](int){});

pid_t child_pid = fork();
switch(child_pid) {
case -1:
std::abort();
case 0: {
// Child process.
execl(args..., nullptr);
abort(); // never get here.
}
default: {
// paren process.
timespec timeout = {};
timeout.tv_sec = max_runtime_sec;
siginfo_t info = {};
int rc = sigtimedwait(&set, nullptr, &timeout);
if(SIGCHLD == rc) {
std::printf("child %u terminated in time with return code %d.\n", static_cast<unsigned>(child_pid), info.si_status);
}
else {
kill(child_pid, SIGTERM);
sigwaitinfo(&set, &info);
std::printf("child %u terminated on timeout with return code %d.\n", static_cast<unsigned>(child_pid), info.si_status);
}
}
}
}

int main() {
start_child(2, "/bin/sleep", "/bin/sleep", "10");
start_child(2, "/bin/sleep", "/bin/sleep", "1");
}

输出:

child 31548 terminated on timeout with return code 15.
child 31549 terminated in time with return code 0.

关于c++ - 创建 3 个子进程并在指定秒数后退出它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54655970/

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