wait()返回0并且errno ="系统调用中断"

时间:2016-09-05 11:23:01

标签: c++ process wait system-calls waitpid

我正在完成一项学校作业,主要涉及创建几个近似pi的子进程,并将其结果写入与子进程ID同名的文本文件。然后,父进程等待所有子进程,并根据存储在文本文件中的值计算pi的平均近似值。

事情很好,但是偶尔(我执行程序的时间大约有10%)wait(NULL)返回-1而errno表示Interrupted system call为其中一个孩子流程。我不知道为什么这似乎是随机发生的。

在下面的代码中,MonteCarlo是一个自定义类,用于处理Pi的近似值。

#include <random>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <unistd.h>
#include "MonteCarlo.h"


int main(int argc,char** argv){
    int approximationProcessCount = 10;
    int approximationRandomCount = 1000;


    for(int i=0; i<approximationProcessCount; i++){
        //pidArray[i] = fork();
        pid_t pid = fork();

        if( pid == -1 ){
            // Fork error
            perror("Fork error");
        }
        else if( pid == 0 ){
            // Child process
            MonteCarlo mc(approximationRandomCount);
            std::string filename(std::to_string(getpid()) + ".txt");
            std::ofstream fs( filename );

            if( !fs ){
                std::cerr << "Cannot open '" << filename << "' for writing." << std::endl;
                return 1;
            }

            fs << mc.approximate();
            fs.flush();
            fs.close();
            return 0;
        }
        else{
            // Parent process
        }
    }

    // Parent process
    double averageApproximation = 0.0;

    for(int i=0; i<approximationProcessCount; i++){
        pid_t childPid = wait(NULL);

        if( childPid == -1 ){
            perror( std::string("Error when waiting for child process [-1] (i=" + std::to_string(i) + ")").c_str());
            continue;
        }
        else if( childPid == 0 ){
            perror( std::string("Error when waiting for child process [0] (i=" + std::to_string(i) + ")").c_str());
            continue;
        }

        std::string filename(std::to_string(childPid) + ".txt");
        std::ifstream fs( filename );

        if( !fs ){
            std::cerr << "Cannot open '" << filename << "' for reading." << std::endl;
            return 1;
        }

        double approximation;
        fs >> approximation;
        fs.close();
        remove(filename.c_str());

        // Calculate average "on the fly"
        averageApproximation += (approximation - averageApproximation)/(i+1);
    }

    std::cout << "Average approximation of Pi = " << averageApproximation << std::endl;

}

当我遇到&#34;错误&#34;时,我得到以下输出(i变化):

Error when waiting for child process [-1] (i=9): Interrupted system call
Average approximation of Pi = 3.14444

我在Mac OSx El Capitan上的XCode中运行它。

0 个答案:

没有答案