计算子进程fork()的进程运行时间

时间:2017-11-10 09:14:52

标签: c unix fork

我正在拥有一个包含1个父进程和3个子进程的程序。我想计算所有子进程的运行时间。

int run_time[3];    // Variable to save the running time of the children process
time_t start[3];        // Variable to help measure the actual time
for ( i = 0; i < 3; i++ )
{
    if( fork() == 0 )           // 3 Children process running
    {
        start[i] = time(NULL);  // Start time of child process
        usleep(1000000);
        run_time[i] = time(NULL) - start[i];        // Calculate run time
        printf("Running time: %d from child\n",run_time[i]);
        exit(0);
    }
}
for ( i2 = 0; i2 < 3; i2++ )    // Waiting all 3 children process finish
    waitpid(-1, NULL, 0);
for ( i3 = 0; i3 < 3; i3++ )    // Printing out run time of children from parent process
    printf("Running time: %d from parent\n",run_time[i3]);

我知道我无法将子进程(我的代码中为run_time[])的计算数据保存到父进程,即使使用全局变量和指针(我也尝试过)。只有一种方法是使用pipe()。这样的事情:int fd[2]然后是pipe(fd)。但是,我不能将pipe()用于超过1个子进程。所以我想好像有另一种方法来计算子进程的运行时间而不使用pipe()?如何将pipe()用于多个子进程。

1 个答案:

答案 0 :(得分:1)

如果第二级粒度对您来说已足够,并且运行时间预计为秒数,则可以将运行时封装在子进程的返回代码中,如下所示:

// return the runtime as an 8-bit integer to the parent
exit(run_time[i] & 0xff);

然后,在父进程中,使用宏WEXITSTATUS来获取退出代码。请参阅wait()系统调用的documentation

  

如果WIFEXITED(stat_val)的值不为零,则此宏将进行计算   子进程的状态参数的低位8位   传递给_exit()或exit(),或子进程返回的值   来自main()。

由于返回码是8位整数,因此仅适用于最长255秒的值。

至于管道,如果你已经知道如何与一个孩子交流并想与多个孩子交流,那么只需使用一系列管道。

程序的修改版本如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <time.h>

int main(int argc, char **argv) {
    int run_time[3];    // Variable to save the running time of the children process
    time_t start[3];        // Variable to help measure the actual time
    pid_t children[3];
    int status;
    int i;

    for ( i = 0; i < 3; i++ ) {
        children[i] = fork();
        if( children[i] == 0 )  {
            start[i] = time(NULL);  // Start time of child process
            usleep(1000000);
            run_time[i] = time(NULL) - start[i];        // Calculate run time
            printf("Running time: %d from child\n",run_time[i]);
            // return the runtime as an 8-bit integer
            exit(run_time[i] & 0xff);
        }
    }
    for ( i = 0; i < 3; i++ ) {   // Waiting all 3 children process finish
        waitpid(children[i], &status, 0);
        if (WIFEXITED(status)) {
            run_time[i] = WEXITSTATUS(status); // use the low-order 8 bits from the exit code
        } else {
            run_time[i] = -1; // unknown run time
        }
    }

    for ( i = 0; i < 3; i++ )    // Printing out run time of children from parent process
        printf("Running time: %d from parent\n", run_time[i]);
}