#include <iostream> // fork and wait #include <unistd.h> #include <signal.h> #include <wait.h> // #include <cmath> using namespace std; long double Pi(int iterations); int main(int argc, char * argv[]) { int procs{10}; int iterations {1'000'000}; if (argc > 1) { int tmp{stoi(argv[1])}; if (tmp > 1 and tmp < 1000) { procs = tmp; } } if (argc > 2) { int tmp{stoi(argv[2])}; if (tmp > 1) { iterations = tmp; } } for(int i = 0; i < procs; ++i) { if (fork() == 0) { srand(time(nullptr)*(i+1)); cout << " process " << i << " got " << Pi(iterations) << endl; return 0; } } for(int i = 0; i < procs; ++i) { wait(nullptr); } } long double Pi(int iterations){ long double pi{0}; long long count{0}; long double x, y; for(int i = 0 ; i < iterations; ++i) { x = rand() / static_cast<long double>(RAND_MAX); y = rand() / static_cast<long double>(RAND_MAX); if (x*x + y*y <= 1) { ++count; } } return static_cast<long double>(count) / static_cast<long double>(iterations) * 4; }