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.
Here is my main function, and the problem exists within the for loop.
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>=0; i--){
childpid = fork();
if(childpid==(pid_t) 0){
//I am the child
cout<<"Child ["<< i <<"] = " << invert[i] <<"."<<endl;
break;
}
}
return 0;
}
A simple modification of your program makes it work. Let the child do the next fork. Each process waits for the one it spawned.
Edit: Skizz objected that each process executed its work before launching the next one. There was no requirement in the question that all the processes be launched first, but the version below does that.