Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
2  
See if help: stackoverflow.com/questions/5339200/… –  enzotib Sep 15 '11 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 '11 at 9:50
    
It is explained in the answer: seems to be ok. –  enzotib Sep 15 '11 at 12:02
    
Copy/paste as answer for accept. –  Coder Sep 15 '11 at 12:33
    
Don't worry, vote up that answer. –  enzotib Sep 15 '11 at 12:48
add comment

1 Answer

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 sychronize 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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.