gpt4 book ai didi

C++通过exec函数杀死子进程,但不杀死父进程和正常运行时间

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

我不知道我目前杀死子进程的方式是否正确。我希望当 child 三的计时器(临时)命中为零时它会杀死所有 child ,然后 parent 打印一条消息而不是退出。另外,我尝试使用 sysinfo 来获取 child 2 的正常运行时间,但是 sysinfo 结构在我运行程序的环境中没有作为成员的正常运行时间。那么,我如何使用 exec 函数从/获取正常运行时间usr/bin/正常运行时间。另外,不要告诉我将所有内容都从主要功能中拆分出来,因为我会在弄清楚如何完成该功能后才这样做。

代码:

#include <string>
#include <ctime>
#include <iostream>
#include <sys/sysinfo.h>
#include <cstdlib>
#include <unistd.h>
#include <sched.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>

using namespace std;

pid_t parent_pid;

void sigquit_handler (int sig) {
assert(sig == SIGQUIT);
pid_t self = getpid();
if (parent_pid != self) _exit(0);
}

int main (string input) {
if (input.empty()) {
input = "10";
}
signal(SIGQUIT, sigquit_handler);
parent_pid = getpid();
int number = atoi(input.c_str());
pid_t pid;
int i;
FILE* fp;
double uptime;

for(i = 0; i < 3; i++) {
pid = fork();
if(pid < 0) {
printf("Error");
exit(1);
}
else if (pid == 0) {
if (i == 0) { //Child 1
sleep(1);
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< endl;
}
else if (i == 1) { //Child 2
sleep(5);
struct sysinfo info;
cout << info.uptime << endl;
}
else { //Child 3
int temp = number;
int minute = temp / 60;
int second = temp - (minute * 60);
sleep(1);
cout << minute << ":" << second << endl;
temp--;
if (temp == 0) {
kill(-parent_pid, SIGQUIT);
}
}
}
else {
cout << "Program is Complete";
}
}
}

最佳答案

Also, I tried using sysinfo to get the uptime in child 2, but the sysinfo struct doesn't have uptime as a member in the environment I am running the program in. So, how do I use a exec function to get uptime from /usr/bin/uptime

你可以设置一个 alarm在一个进程中,并在时间用完时接收 SIGALRM


I want when child three's timer (temp) hit's zero that it kills all the children, then the parent prints a message than exits.

您可能希望先通过调用 setpgrp 使父进程成为组长,这样您就可以使用 kill(0, SIGHUP) 从组中的任何进程向同一组(父进程及其子进程)中的所有进程发送信号。父进程必须为 SIGHUP 安装一个信号处理程序,以便能够在接收到 SIGHUP 或您可能希望用于此目的的任何其他信号时继续存在。

关于C++通过exec函数杀死子进程,但不杀死父进程和正常运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24456693/

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