Skip to content

Instantly share code, notes, and snippets.

@byronhe
Created April 5, 2016 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save byronhe/65c9c323acf8b295c47b9460588b87bb to your computer and use it in GitHub Desktop.
Save byronhe/65c9c323acf8b295c47b9460588b87bb to your computer and use it in GitHub Desktop.
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