Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The nastiest method uses <code>vfork()</code> and lets the different children trample on different parts of memory before exiting; the parent then just adds up the modified bits of memory.</p> <p>Highly unrecommended - but about the only case I've come across where <code>vfork()</code> might actually have a use.</p> <p>Just for amusement (mine) I coded this up:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;sys/wait.h&gt; int main(void) { int i; int array[5]; int square[5]; long sum = 0; srand(time(0)); for (i = 0; i &lt; 5; i++) { array[i] = rand(); if (vfork() == 0) { square[i] = array[i] * array[i]; execl("/bin/true", "/bin/true", (char *)0); } else wait(0); } for (i = 0; i &lt; 5; i++) { printf("in: %d; square: %d\n", array[i], square[i]); sum += square[i]; } printf("Sum: %d\n", sum); return(0); } </code></pre> <p>This works. The previous trial version using '<code>exit(0)</code>' in place of '<code>execl()</code>' did not work; the square array was all zeroes. Example output (32-bit compilation on Solaris 10, SPARC):</p> <pre><code>in: 22209; square: 493239681 in: 27082; square: 733434724 in: 2558; square: 6543364 in: 17465; square: 305026225 in: 6610; square: 43692100 Sum: 1581936094 </code></pre> <p>Sometimes, the sum overflows - there is much room for improvement in the handling of that.</p> <p>The Solaris manual page for '<code>vfork()</code>' says:</p> <blockquote> <p>Unlike with the fork() function, the child process borrows the parent's memory and thread of control until a call to execve() or an exit (either abnormally or by a call to _exit() (see exit(2)). Any modification made during this time to any part of memory in the child process is reflected in the parent process on return from vfork(). The parent process is suspended while the child is using its resources.</p> </blockquote> <p>That probably means the '<code>wait()</code>' is unnecessary in my code. (However, trying to simplify the code seemed to make it behave indeterminately. It is rather crucial that <code>i</code> does not change prematurely; the <code>wait()</code> does ensure that synchronicity. Using <code>_exit()</code> instead of <code>execl()</code> also seemed to break things. Don't use <code>vfork()</code> if you value your sanity - or if you want any marks for your homework.)</p>
 

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