0

I use fork to fork multiple child processes, but for some reason they print over each other here is an example.

Winning Child (5): 0
Child placed peice at: 6,4
 -  -  -  -  -  -  -  - 
Child placed peice at: 2,6
 -  -  -  -  -  -  -  - 
Child placed peice at: 4,1
 -  -  -  -  -  -  -  - 
Child placed peice at: 6,5
 -  -  -  -  -  -  -  - 
Child placed peice at: 3,1
 R  -  -  -  -  -  -  - 
Child placed peice at: 5,4
 R  -  -  -  -  -  -  - 
Child placed peice at: 5,7
 B  B  B  B  -  R  B  R 
 R  R  B  B  R  R  B  B 
Child placed peice at: 2,2

This should print like this:

Winner Parent
Winning Parent (20): 26181
 -  -  -  -  -  -  -  - 
 -  -  -  -  -  -  -  - 
 -  -  -  -  -  -  -  - 
 -  -  -  -  -  -  -  - 
 B  -  -  R  -  -  -  - 
 B  -  -  R  B  -  -  - 
 B  -  -  R  B  B  R  R 
 R  R  -  R  R  B  B  B 

Is there a way to stop the other processes stop their printing when I print the winning board?

4

2 回答 2

2

It is absolutely normal to overlap the print statements in different processes because the run at the same time. You can wait() for the process you want to not overlap the prints with the other processes, but in the case you will lose concurrency.

Another solution would be to use some synchronization mechanisms such as a semaphore or mutex.

于 2013-03-04T21:35:57.183 回答
0

Use sprintf to print to a string, then use printf on that string with a fflush(stdout) to flush to the io stream. This will keep the processes from interleaving output.

I believe this issue is a bigger issue though, what are you trying to do? Can you write the child processes to another file?

于 2013-03-04T21:38:28.317 回答