17

I need to make sure one process executes only in one instance at a time. On Windows you could use named mutex. But I have no idea what to use on Linux.

I think I've seen an approach were app creates an exclusive file, but I can't find it anymore. Do you use regular file functions, busy-loop?

4
  • 2
    See if help: stackoverflow.com/questions/5339200/…
    – enzotib
    Sep 15, 2011 at 9:26
  • There is a first call to fopen which will try to overwrite a possibly locked file, is this ok?
    – Coder
    Sep 15, 2011 at 9:50
  • It is explained in the answer: seems to be ok.
    – enzotib
    Sep 15, 2011 at 12:02
  • Don't worry, vote up that answer.
    – enzotib
    Sep 15, 2011 at 12:48

2 Answers 2

9

If you only want one instance of your app running you can use a lock file. Open it with O_CREAT|O_EXCL flags and it will fail if the file already exists.

If you want to synchronize access to a file use flock. It is also possible to lock parts of files with fcntl. Flock is only for advisory locking meaning a program can ignore the locks and access it anyway. Mandatory locking is possible with fcntl but it requires a special mount option and special file permissions.

semget and semop can be used for interprocess synchronization too.

1

Interprocess mutexes are an optional part of POSIX (see _POSIX_THREAD_PROCESS_SHARED on the unistd.h page) and as they are implemented on Linux you can use them too - see examples.

2
  • The point here is to have mutexes across processes. Is this part of POSIX?
    – Alfe
    Nov 17, 2017 at 15:09
  • yeah, it's one of several Posix IPC mechanisms. That stands for interprocess communications, so the whole idea is to communicate between processes. this looks pretty good: chandrashekar.info/articles/linux-system-programming/…
    – erik258
    Oct 5, 2019 at 1:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .