C – How to tell if a process is starting for the first time

How to tell if a process is starting for the first time… here is a solution to the problem.

How to tell if a process is starting for the first time

I’m developing a program in C where some processes need access to shared memory on embedded linux. This shared memory needs to be initialized when it is created. Any process connected to this memory may crash. When it restarts (probably via linux INIT), it cannot initialize the shared memory again because other processes are using it. How to tell whether the current start of the process that is creating shared memory is the first time or a restart. I came up with an idea to allocate an integer in shared memory where it would be written as a number like 5678956 (anything other than ffffffff or 000000000) to declare that this memory is initialized. But I’m not sure if this works well because critical data is being stored in this memory. Any comments would be appreciated. Thank you.

Solution

You should use both shared semaphores and shared memory segments. Try using O_EXCL| O_CREAT and the initial value 0 open the semaphore through sem_open. If successful, create and initialize the shared memory segment, then publish the semaphore and close it. If opening the semaphore in exclusive mode fails, inclusive opens it and waits for the semaphore to be turned off.

Another solution, if you prefer: use a named file in the file system, with mmap and MAP_SHARED as your shared memory. Start by creating a file with a temporary name and populating it with the initial data it should contain. Then try to link it to your real name. If link fails due to EEXIST, you are not the first process and you can delete the temporary file and open and map the existing file. If Link succeeds, you are the first process.

Related Problems and Solutions