Reputation: 9
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
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:
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
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
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