user499403
user499403

Reputation: 9

Linux mutex to check that the program is already running?

Can anyone tell me why the the following does not work as an example of a mutex under Linux

#include <pthread.h>
int main (){
pthread_mutex_t start;
if (pthread_mutex_init(&start, NULL) != 0){
     printf("err!");
     return(1);
}
if (pthread_mutex_lock(&start) != 0){
     printf("err!");
     return(1);
}

pthread_mutex_unlock(&start);
pthread_mutex_destroy(&start);
}

Upvotes: 0

Views: 1204

Answers (3)

user50049
user50049

Reputation:

The best way that I've found for one process to check and see if another is alive and running is to use a lock file, as was suggested in comments with the addition of signals.

This is useful when program B should not bother starting if program A is not already started, alive and responsive, or when program A is not responsible for starting program B but should do something different if program B doesn't start in a set amount of time. That's actually a very common scenario.

Try this:

  • Program A starts, writes its PID to /var/run/a.pid
  • Program B starts, writes its PID to /var/run/b.pid
  • Program B reads /var/run/a.pid and sends it a SIGUSR1
  • Program A's signal handler for SIGUSR1 reads /var/run/b.pid and sends it a SIGUSR1 as an ACK
  • Program B knows program A is running and can continue
  • Program A knows program B has started, and can alter its behaviour

That is extremely simplified and basic IPC, but works. A much more elegant approach would be a shared memory segment between the processes via mmap() but even then you should not trust a lock as as sign that the other process is actually responsive, especially without dealing with starvation in the second process. The reverse situation also holds true.

This is also a very POSIX centric answer, if it doesn't apply, please describe your platform in more detail.

Upvotes: 0

MarkR
MarkR

Reputation: 63558

The pthread mutex is intended for use in threads in a single process; it might also work if it's located in shared memory, but the way you allocate it above, neither will be true.

So invoking two copies of the program, creates two mutexes, each takes their own and everybody is happy - except that isn't what you want.

I think the simplest way to allow only one copy is to open a file for writing and take an exclusive file lock on it (see flock()).

Another possibility is to try to bind a unix socket in the abstract namespace; see man unix(7), however this is Linux-specific.

Upvotes: 0

Wim
Wim

Reputation: 11252

pthread mutexes are for synchronizing threads within one program. If you start this program twice, you get two different mutexes. For synchronizing between multiple processes, there are other tools (file locks are probably the easiest in this situation).

Upvotes: 8

Related Questions