Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to wait until all child processes called by fork() complete?
    text
    copied!<p>I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment.</p> <p>Here is as a code I use:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;sys/time.h&gt; #include &lt;sys/wait.h&gt; using namespace std; struct timeval first, second, lapsed; struct timezone tzp; int main(int argc, char* argv[])// query, file, num. of processes. { int pCount = 5; // process count gettimeofday (&amp;first, &amp;tzp); //start time pid_t* pID = new pid_t[pCount]; for(int indexOfProcess=0; indexOfProcess&lt;pCount; indexOfProcess++) { pID[indexOfProcess]= fork(); if (pID[indexOfProcess] == 0) // child { // code only executed by child process // magic here // The End exit(0); } else if (pID[indexOfProcess] &lt; 0) // failed to fork { cerr &lt;&lt; "Failed to fork" &lt;&lt; endl; exit(1); } else // parent { // if(indexOfProcess==pCount-1) and a loop with waitpid?? gettimeofday (&amp;second, &amp;tzp); //stop time if (first.tv_usec &gt; second.tv_usec) { second.tv_usec += 1000000; second.tv_sec--; } lapsed.tv_usec = second.tv_usec - first.tv_usec; lapsed.tv_sec = second.tv_sec - first.tv_sec; cout &lt;&lt; "Job performed in " &lt;&lt;lapsed.tv_sec &lt;&lt; " sec and " &lt;&lt; lapsed.tv_usec &lt;&lt; " usec"&lt;&lt; endl &lt;&lt; endl; } }//for }//main </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload