Что я делаю не так с системными вызовами wait (), fork () и times ()? - PullRequest
0 голосов
/ 06 ноября 2018

Я хочу создать программу, которая разветвляется 6 раз : первый ребенок , который разветвляется, разветвляет других 5 детей (внуков) и устанавливает их в бесконечный цикл, более того, я хочу установить обратный отсчет в 5 секунд, в то время как первый ребенок делает форк. Когда обратный отсчет заканчивается, я посылаю сигнал первому ребенку, чтобы он прекратил 5 внуков и печатал, сколько пользовательского времени и системного времени (первый ребенок взял).
Я думал о том, чтобы сделать что-то вроде этого: enter image description here

сигнал, который я отправлю первому дочернему элементу после окончания обратного отсчета, будет SIGUSR1, после того, как он получит сигнал, печатает пользовательское и системное время через системный вызов times (), а затем завершает всю группу процессов с помощью killpg (getpgrp) (), SIGTERM);

вот мой код:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/signal.h>
#include <sys/times.h>

void print_time(int signum){
    struct tms t;
    perror("about to print time");
    if ((times(&t)) == -1)
    {
        perror("error times");
        exit(1);
    }

    else
    {
    printf("usertime: %f , systemtime:%f, usertime+systemtime: %f \n",  (double)t.tms_utime, (double)t.tms_stime, (double)t.tms_stime + (double)t.tms_utime);
    killpg(getpgrp(), SIGTERM); //finish the program by killing the whole group id
    }
}


int main()
{

    pid_t ppid = fork();
    if (ppid == 0)
    { //first child
        size_t count = 5;
        for (size_t i = 0; i < count; i++)  //fork 5 children(or 5 grandchildren) from  the first child and set them in an endless loop
        {

            pid_t pid = fork();
            if (pid == 0)
            {

                while (1)
                {
                }
            }

            else if (pid < 0)
            {
                perror("error forking from child ");
            }
        }
        if (signal(SIGUSR1, print_time) == SIG_ERR)   //set signal to the first child  so it print the time gathered by wait()
        {
            perror("cannot create signal");
            exit(1);
        }
        wait(NULL); //wait for the 5 children and gather time
    }

    else if (ppid > 0)
    { //parent
        if (signal(SIGUSR1, SIG_IGN) == SIG_ERR)   //ignore signal so it doesnt affect the parent
        {
            perror("cannot create signal parent");
            exit(1);
        }
        sleep(5);
        perror("going good");
        kill(ppid, SIGUSR1); //send signal to the process group but the parent and grandchildren doesnt get affected  

    }
    else
    {
        perror("error");
        exit(1);
    }

    return 0;
}

Но я получаю только следующий вывод:

pc@pc-host:~/Git/so/p1$ about to print time: Success
usertime: 0.000000 , systemtime:0.000000, usertime+systemtime: 0.000000

почему все нули? согласно этой справочной странице http://man7.org/linux/man-pages/man2/times.2.html

Поле tms_utime содержит время ЦП, затраченное на выполнение инструкций. Обращения к процессу вызова. Поле tms_stime содержит процессор время, потраченное на выполнение внутри ядра при выполнении задач на от имени вызывающего процесса.

...