簡體   English   中英

創建並獲取多個子進程

[英]Create and Reap Multiple Child Processes

我一直無法弄清楚如何派生多個(從10到200之間的任何地方)子進程,並讓父進程等待所有它們完成。 我正在嘗試對它們的累積執行時間進行基准測試。

盡管我盡了最大的努力,但我得到的結果卻非常隨機,當我頂着看它時,過程會顯示為“ Z”(僵屍)。

我的代碼如下,任何幫助將不勝感激。

int child_pid;
int status, wait_pid;

for(i = 0; i < instances; i++){
    if((child_pid = fork()) < 0){ // an error occured
        fprintf(stderr, "Fork failed\n");
        exit(EXIT_FAILURE);
    }
    if(child_pid == 0){ 
        // Child process --------------------------------------------------
        fprintf(stdout, "Child with PID: %d is in if code.", getpid());

        // Calculate pi using statistical methode across all iterations
        for(i=0; i<iterations; i++){
            x = (random() % (RADIUS * 2)) - RADIUS;
            y = (random() % (RADIUS * 2)) - RADIUS;
            if(zeroDist(x,y) < RADIUS){
                inCircle++;
            }

            inSquare++;
        }

        /* Finish calculation */
        pCircle = inCircle/inSquare;
        piCalc = pCircle * 4.0;

        /* Print result */
        fprintf(stdout, "pi = %f\n", piCalc);

        _Exit(EXIT_SUCCESS); //child is done ------------------------------
    }
}

//Parent Process
while ((wait_pid = wait(&status)) > 0){
    printf("Exit status of %d was %d \n", (int)wait_pid, status);
}

fprintf(stdout, "Bye from: %d.\n", getpid());
return 0;

編輯:

要衡量我的結果,我只是使用Linux time命令從命令行調用該程序。

> /usr/bin/time ./pi-sched

編輯2:

我的代碼其余部分包含以下兩個功能以及一堆命令行解析和設置過程; 與計算無關。

inline double dist(double x0, double y0, double x1, double y1){
    return sqrt(pow((x1-x0),2) + pow((y1-y0),2));
}

inline double zeroDist(double x, double y){
    return dist(0, 0, x, y);
}

當我頂着觀看時,進程顯示為“ Z”(僵屍)。

那是因為除非您完成for(i = 0; i < instances; i++){循環,否則您不會開始等待子進程。 要盡快等待子進程,您可以在此for()循環中將該調用放入waitpid(-1, &status, WNOHANG) ,如果沒有終止的子進程,則此waitpid()將立即返回。

我得到了非常隨機的結果

程序的執行時間取決於以下代碼的昂貴程度:

        x = (random() % (RADIUS * 2)) - RADIUS;
        y = (random() % (RADIUS * 2)) - RADIUS;
        if(zeroDist(x,y) < RADIUS){
            inCircle++;
        }

由於xy是一些隨機值,因此上述代碼的執行時間也可能會隨機變化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM