lock-emu.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. #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. #define BUF_SIZE 32
  23. int tryLock(char * file){
  24. return open(file, O_CREAT | O_EXCL | O_WRONLY, 0666);
  25. }
  26. int main(int argc, char* argv[]){
  27. int fd;
  28. char user[BUF_SIZE];
  29. if(argc < 2){
  30. printf("arguments are not right!\n");
  31. exit(-1);
  32. }
  33. do{
  34. fd = tryLock(argv[1]);
  35. if(fd > 0){
  36. getlogin_r(user, BUF_SIZE);
  37. int len = strlen(user);
  38. user[len] = '\0';
  39. write(fd, user, len+1);
  40. break;
  41. } else {
  42. // someone is holding the lock...
  43. fd = open(argv[1], O_RDONLY);
  44. if(fd > 0){
  45. read(fd, user, BUF_SIZE);
  46. printf("%s is holding the lock, waiting ...\n", user);
  47. }
  48. }
  49. sleep(10);
  50. } while(1);
  51. return 0;
  52. }