Note that there are some explanatory texts on larger screens.

plurals
  1. POfork() function in linux
    text
    copied!<pre><code>#include&lt;stdio.h&gt; #include&lt;sys/types.h&gt; #include&lt;unistd.h&gt; void main() { int i = 1; pid_t child_pid; printf("The main program process ID is %d", (int) getpid()); printf("%d", i); child_pid = fork(); if (child_pid != 0) { i++; printf("%d", i); printf("This is the parent process, with ID %d \n", (int) getpid()); printf("The child process is %d ", (int) child_pid); } else { printf("%d", i); printf("This is the child process, with ID %d \n", (int) getpid()); } } </code></pre> <p>I'm running this program using the C language, using the <code>fork()</code> function. As I understand it, when a process calls <code>fork()</code>, a duplicate process, called a child process, is created. The parent process continues executing from the point that <code>fork()</code> was called, and the child process, too, executes the same program from the same place.</p> <p>So when I run my program, I expect the output be like the following text:</p> <pre><code>The main program process ID is 181411This is the child process, with ID 1815 The main program process ID is 18142This is the parent process,with ID 1814 The child process is 1815 </code></pre> <p>But I actually see this output:</p> <pre><code>The main program process ID is 181411This is the child process, with ID 1815 The main program process ID is 181412This is the parent process,with ID 1814 The child process is 1815 </code></pre> <p>It means that the child executes the program first!!! When I put <code>\n</code> at the end of each <code>printf</code> statement the output is correct!!!</p> <p>I've tried it on the Fedora v12 and rhel 5 distributions. Is there any logical relation between the <code>\n</code> and the <code>fork()</code> operation? How I can solve this problem?</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