Reputation: 65
I created processes. One of them prints "1" 30 times
. Another prints "2" 30 times
.I want these processes to print their numbers in turn.
Like this:
1
2
1
2
...
But every time I run the program, the numbers are displayed differently:
1,2,2,1; 1,2,1,2,2,1,1,2.
Can someone tell me,please,how to solve this problem?
Upvotes: 2
Views: 120
Reputation: 92
After seen these comments, I feel that I need to work out my own answer.
Since two or n processes are independent of each other, they don't know about the existence of other processes and so we need some way to make them communicate without breaking the system.
This is known as IPC or Inter Process Communication and one way to accomplish this is shared memory
. That is a region of memory which can be shared between two or more processes.
But how we access that shared memory
, with pointers and we could do something like this:
The father process will allocate a chunk of shared memory with mmap
. Now this region can be accessed with pointers by processes to talk between them and share data.
Upvotes: 1
Reputation: 40604
Processes run entirely independent of each other. They may run simultaneously, they may run one after the other, they may run one at a time with a switch between them at non-deterministic times, or any mixture of these "modes". There is simply no telling which process runs when.
As such, the only way to make processes cooperate safely is to make them communicate. And here you have a lot of options:
Pipes allow you to send unidirectional messages between two forked processes. This communication is blocking by default.
Locks allow one process exclusive access to whatever resource you like.
Shared memory regions allow processes to send each other data without the need to wait for the other process.
Files can be used instead of locks or shared memory regions. They are much more heavy-weight, but don't require the processes to be of common decent.
Whatever communication you use, you must use one to get correctly coordinated behavior.
Upvotes: 2
Reputation: 7919
This is an expected behaviour. After the process is forked (which is a quite small duration), two processes will print 2 or 1 depending on their id's. Because sleep method resolution is 1 second and time difference between two forked processes is too small compared to this, the order of printing id's will not be definite because the two processes will call printf function is quite close times (on the micro-second resolution maybe). To be able to order printing numbers, you can add a delay to one of the processes:
if(pid==0)
{
for(i=1;i<=30;i++)
{
printf("%s\n","2");
sleep(2);
}
}
else
{
sleep(1);
for(i=1;i<30;i++)
{
printf("%s\n","1");
sleep(2);
}
}
As a result, forked processes are not expected to run in a perfect synchrony. In order to achive interprocess synchrony you can use inter process level shared variables: https://stackoverflow.com/a/13274800/2183287
Upvotes: 3