1 #include<unistd.h> 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<sys/stat.h> 5 #include<fcntl.h> 6 #include<string.h> 7 8 #define BUF_SIZE 32 9 10 int tryLock(char * file){ 11 return open(file, O_CREAT | O_EXCL | O_WRONLY, 0666); 12 } 13 14 int main(int argc, char* argv[]){ 15 int fd; 16 char user[BUF_SIZE]; 17 if(argc < 2){ 18 printf("arguments are not right!\n"); 19 exit(-1); 20 } 21 22 do{ 23 fd = tryLock(argv[1]); 24 if(fd > 0){ 25 getlogin_r(user, BUF_SIZE); 26 int len = strlen(user); 27 user[len] = '\0'; 28 write(fd, user, len+1); 29 break; 30 } else { 31 // someone is holding the lock... 32 fd = open(argv[1], O_RDONLY); 33 if(fd > 0){ 34 read(fd, user, BUF_SIZE); 35 printf("%s is holding the lock, waiting ...\n", user); 36 } 37 } 38 sleep(10); 39 } while(1); 40 41 return 0; 42 } 43 44