xref: /XiangShan/scripts/utils/lock-emu.c (revision 367512b707c976b7ff3fa2e0a4cf1b35a5c1d3c2)
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             write(fd, user, strlen(user));
27             break;
28         } else {
29             // someone is holding the lock...
30             fd = open(argv[1], O_RDONLY);
31             if(fd > 0){
32                 read(fd, user, BUF_SIZE);
33                 printf("%s is holding the lock, waiting ...\n", user);
34             }
35         }
36         sleep(10);
37     } while(1);
38 
39     return 0;
40 }
41 
42