xref: /XiangShan/scripts/utils/lock-emu.c (revision c6d439803a044ea209139672b25e35fe8d7f4aa0)
1 /***************************************************************************************
2 * Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3 *
4 * XiangShan is licensed under Mulan PSL v2.
5 * You can use this software according to the terms and conditions of the Mulan PSL v2.
6 * You may obtain a copy of Mulan PSL v2 at:
7 *          http://license.coscl.org.cn/MulanPSL2
8 *
9 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
10 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
11 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
12 *
13 * See the Mulan PSL v2 for more details.
14 ***************************************************************************************/
15 
16 #include<unistd.h>
17 #include<stdio.h>
18 #include<stdlib.h>
19 #include<sys/stat.h>
20 #include<fcntl.h>
21 #include<string.h>
22 
23 #define BUF_SIZE 32
24 
25 int tryLock(char * file){
26     return open(file, O_CREAT | O_EXCL | O_WRONLY, 0666);
27 }
28 
29 int main(int argc, char* argv[]){
30     int fd;
31 	char user[BUF_SIZE];
32 	if(argc < 2){
33 	    printf("arguments are not right!\n");
34 		exit(-1);
35 	}
36 
37     do{
38         fd = tryLock(argv[1]);
39         if(fd > 0){
40             getlogin_r(user, BUF_SIZE);
41             int len = strlen(user);
42             user[len] = '\0';
43             write(fd, user, len+1);
44             break;
45         } else {
46             // someone is holding the lock...
47             fd = open(argv[1], O_RDONLY);
48             if(fd > 0){
49                 read(fd, user, BUF_SIZE);
50                 printf("%s is holding the lock, waiting ...\n", user);
51             }
52         }
53         sleep(10);
54     } while(1);
55 
56     return 0;
57 }
58 
59