Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ensure_single_process
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
void ensure_single_process(const char * id){
struct sockaddr_un sun;
if(NULL==id || strlen(id)+1>sizeof(sun.sun_path)){
return ;
}
memset(&sun,0,sizeof(sun));
sun.sun_family=AF_UNIX;
strcpy(sun.sun_path+1,id); //abstract namespace.
int s = socket(AF_UNIX, SOCK_STREAM, 0);
if(bind(s,(struct sockaddr *) &sun,sizeof(sun))){
printf("another process is running under %s. exiting ...\n",id);
exit(1);
}
printf("ok, i am the only one under %s. running ...\n",id);
}
int
main(int argc, char **argv)
{
int s;
struct sockaddr_un sun;
if (argc != 2 || strlen(argv[1]) + 1 > sizeof(sun.sun_path)) {
fprintf(stderr, "usage: %s abstract-path\n", argv[0]);
exit(1);
}
ensure_single_process(argv[1]);
pause();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.