0

如何使用 exec 命令从 /usr/bin/uptime 获取每 5 秒显示一次的正常运行时间?如何让我的 3 个孩子通过管道写入父级,然后写入父级中的标准输出?

到目前为止,我的项目有:

#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";
    }
}
 }
4

0 回答 0