简体   繁体   中英

Synchronization between two processes using semaphores in c

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(sem() call system) in order to ensure that the first process always starts first and the second process starts only after the first process has finished writing?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM