static int vipalias_lock() { int ret = -1; /* we create a symlink with our PID (a dummy symlink). If this fails, we do a readlink and check if the process is alive. If not, we erase the symlink and try again. If the process is alive, we sleep 2 seconds. */ char pidstr[10]; snprintf (pidstr,sizeof(pidstr)-1,"%u",getpid()); while (1){ if (symlink(pidstr,lockfile)!=-1){ ret = 0; break; }else if (errno != EEXIST){ fprintf (stderr,"Can't create lockfile %s (%s)\n" ,lockfile,strerror(errno)); break; }else{ char buf[100]; int len = readlink(lockfile,buf,sizeof(buf)); if (len > 0){ buf[len] = '\0'; pid_t pid = atoi(buf); if (kill(pid,0)==-1){ unlink (lockfile); }else{ // Process exist fprintf (stderr,"vipalias can't lock %s, waiting for process %u\n" ,lockfile,pid); sleep(2); } } } } return ret; } static void vipalias_unlock() { unlink (lockfile); }