Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Ok, first of all you're not getting a total random intermangled words of HELLO and WORLDs because stdout is buffered.</p> <p>So your parent is printing HELLO until that buffer gets full, and then that whole buffer ends up on your screen. Same for the child.</p> <p>If you want to synchronize this, you could use 2 pipes to communicate between your parent and child. e.g. </p> <ul> <li>parent prints "HELLO", </li> <li>child starts reading from the pipe1. </li> <li>parent writes a character to the pipe1 to signal that the child should print "WORLD"</li> <li>parent starts reading from the pipe2</li> <li>child reads from pipe1, prints "WORLD"</li> <li>child writes a character to pipe2 to signal that the parent should print "HELLO"</li> <li>repeat the above</li> </ul> <p>-</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; void err(const char *error) { perror(error); exit(1); } void run_handler(int readfd,int writefd,const char *message) { for(;;) { char ch; int i; if((i = read(readfd,&amp;ch,1)) == 0) break; else if(i &lt; 0) err("read"); //important: fflush the text so it ends up in the output //and not in an internal FILE* buffer. if(fputs(message,stdout) == EOF || fflush(stdout) == EOF) break; if(write(writefd,&amp;ch,1) != 1) err("write"); } } int main() { int pipe1[2]; int pipe2[2]; pid_t pid; if(pipe(pipe1) != 0) err("pipe1"); if(pipe(pipe2) != 0) err("pipe2"); if((pid = fork()) == 0 ) { //write one char to the parent to get it started char ch = '.'; if(write(pipe1[1],&amp;ch,1) != 1) err("write"); //close the pipe ends we don't need close(pipe1[0]); close(pipe2[1]); run_handler(pipe2[0],pipe1[1],"WORLD\n"); }else if(pid &gt; 0) { //close the pipe ends we don't need close(pipe1[1]); close(pipe2[0]); run_handler(pipe1[0],pipe2[1],"HELLO "); } else { err("fork"); } return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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