Write a C program that forks, with the parent reading stdin and parsing the input stream into words, then passing the words one by one to the child. The child writes the words to stdout.
The words are passed through a buffer in shared memory. The Peterson Algorithm mutual-exclusion code is used to safely share the buffer, locking it while the buffer contents are being changed.
Write the code to implement Peterson's Algorithm. A struct containing the required variables is provided. This struct is also placed in shared memory.
The child needs to know when the buffer is full so that it can read from it, and the parent needs to know when the buffer is empty so that it can write to it. For this project, a null string means that the buffer is empty.
If the parent locks the buffer and finds that it does not contain the null string, it unlocks the buffer and tries again later. Otherwise, it overwrites the null string with the next word.
If the child locks the buffer and finds that it does not contain the null string, it reads the word, prints it, and overwrites the buffer with the null string.
Both processes are expected to terminate cleanly. The parent knows that input has ended when fgets returns NULL, and the parent must then inform the child that there are no more words to come. The parent sets the done flag to signal this condition.
The child should terminate only after the done flag is set and the buffer is empty.
struct Peterson {
volatile int interested[2];
volatile int turn;
};
struct SharedMemory {
struct Peterson peterson ;
int done ;
char word[WORD_SIZE] ; // if word[0]=='\0' there is not word
} ;
The code for the Peterson algorithm is in the file peterson.c. It uses struct Peterson. This data structure is in memory shared between two processes. To organize the share memory, which is just an array of bytes as would be any memory, the share memory is cast to strict SharedMemory.
The implementation in peterson.c will use the is_held_g that is 0 when the lock is not held and 1 when the lock is held. This is for debugging, however it can be used to check for the error of releasing a lock that is not held.

author: burton rosenberg
created: 2 oct 2026
update: 2 oct 2026