Home > database >  Synchronization between two processes using semaphores in c
Synchronization between two processes using semaphores in c

Time:01-29

I have a task in which I have to write a program in C language that manages access and reading/writing to a file.

When the program starts it should create two processes(using fork()).

-The first process will be responsible for the initial write to the file(The file is a text file with 2000 random characters from a to z).

-The second process will be responsible for reading from the file ,after the first process has finished writing.

My question is :

How can I synchronize the execution order by using semaphores in order to ensure that the first process always starts first and the second process starts only after the first process has finished writing?

CodePudding user response:

I can recommend using binarysemaphores: // https://www.freertos.org/xSemaphoreCreateBinary.html

https://controllerstech.com/how-to-use-binary-semaphore-in-stm32/

If you are working in an embedded context i would recommend using Tasknotification since they are less ram hungry and therefore may be more fitting in a less powerfull system. https://www.freertos.org/RTOS-task-notifications.html

CodePudding user response:

Semaphores are inherited across a fork(). (POSIX.1-2017)

So, one easy approach is to initialize the semaphore to zero before the reader exists, fork() the child reader, which waits on the semaphore before reading. When the parent writer is finished, it posts the semaphore, releasing the child.

  • Related