2017-11-10 39 views
0

私は1つの親プロセスと3つの子プロセスを持つプログラムを持っています。そして、私はすべての子プロセスの実行時間を計算したいと思います。子プロセスfork()のプロセス実行時間を計算する

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()を使用している方法は1つだけです。このようなもの:int fd[2]、次にpipe(fd)しかし、1つ以上の子プロセスにpipe()を使用することはできません。子プロセスの実行時間を計算する別の方法があたかもpipe()を使用していないかのように私は望んでいますか?そして、複数の子プロセスにどのようにpipe()を使用することができますか?

答えて

1

セカンドレベルの粒度はあなたのために十分であるとランタイムが秒のオーダーになることが予想されている場合は、このように、子プロセスのリターンコードでランタイムをカプセル化することができます

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

親プロセスでは、WEXITSTATUSマクロを使用して終了コードを取得します。 WIFEXITEDの値(stat_val)が非ゼロである場合、このマクロは、子プロセス が渡さことstatus引数の下位8ビットに を評価し、

wait()システムコールのdocumentationを参照_exit()またはexit()、または子プロセスがmain()から を返した値。

リターンコードは8ビットの整数なので、最大255秒の値でのみ機能します。

パイプについては、既に1人の子供と通信する方法を知っていて、複数の子供と通信したい場合は、単にパイプの配列を使用してください。

あなたのプログラムの修正版は、次のとおりです。

#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]); 
} 
+0

をあなたにたくさんありがとうございました。私のコードが動作します:D。私は依然として質問したいと思います:なぜあなたはそのようなexit()を書いていますか?どのように役立ちますか? WIFEXITED(ステータス)は何を意味しますか? – Someonewhohaveacat

関連する問題