Advertisement
lolhopen

OS LAB 4 LIN

Nov 4th, 2023
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <stdlib.h>
  7.  
  8. int main() {
  9. char buffer[256] = "";
  10. struct flock lock = {F_WRLCK, SEEK_SET, 0, 0, getpid()};//from start (0) 'til end (0) of file
  11. int opened = open("./forlab4.txt", O_RDWR);
  12. if (opened != -1) {
  13. if (fcntl(opened, F_SETLK, &lock) == -1) {
  14. system("clear");
  15. printf("\033[9B\033[15C\033[91mLocking is unavailable yet.\n\033[25CWaiting.\n");//\n is needed as it flushes stdout immediately instead of end of programm
  16. fcntl(opened, F_SETLKW, &lock);
  17. }
  18. system("clear");
  19. printf("\033[9B\033[15C\033[91mFile is successfully locked.\033[39m\n");
  20.  
  21. int len;
  22. len = read(opened, buffer, 255);
  23. write(1, buffer, len);
  24.  
  25. sleep(7);
  26. fcntl(opened, F_UNLCK, &lock);
  27. system("clear");
  28. printf("\033[9B\033[14C\033[91mFile is successfully unlocked.\n");
  29.  
  30. close(opened);
  31. return 0;
  32. } else {
  33. system("clear");
  34. printf("\033[9B\033[17C\033[91mFile can not be opened.\n\033[11CProgram will be terminated shortly.\n");
  35. }
  36. printf("\033[39m");
  37. return 0;
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement