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