title: Using fork() to output 1 array element per child, C++
body: <p>I have an assignment that is to take in a string from the command line, reverse it and output each character in a separate child process using fork().  I'm just not getting the correct output from the fork() calls.  The problem is that indexes get jumbled up on output, like 3, 1, 2, 0 when it should just be 3,2,1,0 ... etc...  What makes it more confusing is it randomly is successful when the word is 3 characters long (but not always), but routinely is incorrect for words with 4+ characters.  The loop works correctly without the fork() call.</p>
  
  <p>Here is my main function, and the problem exists within the for loop.</p>
  
  <pre><code>int main(int argc, char **argv){
      pid_t childpid = 0;
      int i;
      char* invert = new char[strlen(argv[1])+1];
      int invert_length = strlen(argv[1]);
      strcpy(invert, argv[1]);
      for(i=invert_length-1; i&gt;=0; i--){
          childpid = fork();
          if(childpid==(pid_t) 0){
              //I am the child            
              cout&lt;&lt;"Child ["&lt;&lt; i &lt;&lt;"] = "  &lt;&lt; invert[i] &lt;&lt;"."&lt;&lt;endl;
              break;
          }
      }   
      return 0;
  }
  </code></pre>