Guest User

Untitled

a guest
Nov 17th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/file.h>
  4. #include <unistd.h>
  5.  
  6. int main(int argc, char *argv[])
  7. {
  8. int k=0;
  9. k=atoi(argv[1]);
  10. struct flock fl;
  11. int fd;
  12. char *buf=malloc(sizeof(char)*512);
  13.  
  14. fl.l_type = F_WRLCK; /* F_RDLCK, F_WRLCK, F_UNLCK */
  15. fl.l_whence = SEEK_SET; /* SEEK_SET, SEEK_CUR, SEEK_END */
  16. fl.l_start = 0; /* Offset from l_whence */
  17. fl.l_len = 0; /* length, 0 = to EOF */
  18. fl.l_pid = getpid(); /* our PID */
  19.  
  20. int chPid=fork();
  21. if(chPid)
  22. {
  23.  
  24.  
  25. fd = open("FILENAME.txt", O_RDWR);
  26. fcntl(fd, F_SETLKW, &fl); /* F_GETLK, F_SETLK, F_SETLKW */
  27.  
  28. int st=0;
  29. read(fd,buf,512);
  30. st=atoi(buf);
  31. st++;
  32. printf("This is child :%d\n",st);
  33.  
  34. fl.l_type = F_UNLCK; /* tell it to unlock the region */
  35. fcntl(fd, F_SETLK, &fl); /* set the region to unlocked */
  36. close(fd);
  37. }
  38. int fd2=open("FILENAME.txt", O_RDWR);
  39. while(fcntl(fd2, F_SETLKW, &fl)<0)
  40. {
  41. //printf("ni še");
  42. sleep(1);
  43. }
  44. read(fd2,buf,512);
  45. int st2=atoi(buf);
  46. printf("This is parent :%d\n",st2);
  47.  
  48. //printf("Tuki še dela\n");
  49.  
  50.  
  51. return 0;
  52. }
Add Comment
Please, Sign In to add comment