I am working on a program by C that some processes need to access a shared memory on an embed linux. This shared memory needs to be initialized when it was created. Any process attaching to this memory may crash. When it restarted (may be by linux INIT), it must not initialize the shared memory again since other processes are using it. How to tell if current starting of the process that is creating shared memory is the first time or restarted. I came up with an idea that allocates a integer in shared memory where will be written as a number like 5678956 (any number other than ffffffff or 00000000) to claim this memory has been initialized. But I am not sure if this is working well since the critical data is storing this memory. Any advice would be appreciated. Thanks.
Share
You should use both a shared semaphore and shared memory segment. Attempt opening the semaphore with
sem_openusingO_EXCL|O_CREATand an initial value of 0. If that succeeds, create and initialize the shared memory segment, then post the semaphore and close it. If opening the seamphore in exclusive mode failed, open it non-exclusive and wait on the semaphore, then close it.Another solution, if you prefer: Use a named file in the filesystem with
mmapandMAP_SHAREDfor your shared memory. First create the file with a temporary name and populate it with the initial data it should contain. Then attempt tolinkit to the real name. Iflinkfails withEEXIST, you’re not the first process, and you can just delete your temp file and open and map the existing one. Iflinksucceeds, you are the first process.