ChaniLastnamé
ChaniLastnamé

Reputation: 533

C - Creating two processes which obtains 50 unique integers

So I am trying to figure out the logic for this homework assignment. Can someone help? From what I understand I have to create 2 processes which reads the N from the given file and increment that N number by 1. The part I don't understand is how I assign odd and even integers to these 2 processes when both of them are doing the exact same thing.

Write a simple sequence-number system through which two processes, P1 and P2, can each obtain 50 unique integers, such that one receives all the odd and the other all the even numbers. Use the fork() call to create P1 and P2. Given a file, F, containing a single number, each process must perform the following steps:

a. Open F.
b. Read the sequence number N from the file.
c. Close F.
d. Output N and the process' PID (either on screen or test file).
e. Increment N by 1
f. Open F.
g. Write N to F.
h. Flush F.
i. Close F

Upvotes: 0

Views: 256

Answers (2)

paxdiablo
paxdiablo

Reputation: 881223

Without some form of inter-process communication (IPC), there's no real way to guarantee that a single process won't do its read-increment-write action twice in a row, so that it ends up outputting an even/odd pair.

So my suggestion is to start reading up on IPC, semaphores would be a good start.

In order to guarantee alternating processes, semaphores on their own may not be enough. You may need to have something like shared memory as well which indicates which process (the odd or even one) should next read the file.

In that case, each process would grab the semaphore and check the shared memory. If it was its turn to run, it should perform the file operations, change shared memory then release the semaphore. If it was not its turn to run, it should just release the shared memory and try again.

That, of course, introduces the possibility of livelock so it may be necessary to introduce a (very) short delay if you're releasing the semaphore because it wasn't your time.

And remember to set up the shared memory before you fork the two processes.


The other possibility is to use the advisory locking call flock so only one process at a time can get at the file.

Upvotes: 1

Astra Bear
Astra Bear

Reputation: 2738

The two processes can be similar but not exactly the same. In each process have a loop at the start that reads N from the file. In one process, if N is odd then continue, but if N is even, sleep for a second say then go back to the start of the loop.

In the other process, reverse the odd/even above.

Upvotes: 0

Related Questions