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?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Coder
  • 457
  • 2
  • 6
  • 10

2 Answers2

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.

Gabriel Staples
  • 2,192
  • 1
  • 24
  • 31
stribika
  • 5,374
  • 5
  • 30
  • 35
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.

Milan Kerslager
  • 210
  • 2
  • 3
  • The point here is to have mutexes across processes. Is this part of POSIX? – Alfe Nov 17 '17 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: http://www.chandrashekar.info/articles/linux-system-programming/introduction-to-linux-ipc-mechanims.html – erik258 Oct 05 '19 at 01:45