Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/file.h>
- #include <unistd.h>
- int main(int argc, char *argv[])
- {
- int k=0;
- k=atoi(argv[1]);
- struct flock fl;
- int fd;
- char *buf=malloc(sizeof(char)*512);
- fl.l_type = F_WRLCK; /* F_RDLCK, F_WRLCK, F_UNLCK */
- fl.l_whence = SEEK_SET; /* SEEK_SET, SEEK_CUR, SEEK_END */
- fl.l_start = 0; /* Offset from l_whence */
- fl.l_len = 0; /* length, 0 = to EOF */
- fl.l_pid = getpid(); /* our PID */
- int chPid=fork();
- if(chPid)
- {
- fd = open("FILENAME.txt", O_RDWR);
- fcntl(fd, F_SETLKW, &fl); /* F_GETLK, F_SETLK, F_SETLKW */
- int st=0;
- read(fd,buf,512);
- st=atoi(buf);
- st++;
- printf("This is child :%d\n",st);
- fl.l_type = F_UNLCK; /* tell it to unlock the region */
- fcntl(fd, F_SETLK, &fl); /* set the region to unlocked */
- close(fd);
- }
- int fd2=open("FILENAME.txt", O_RDWR);
- while(fcntl(fd2, F_SETLKW, &fl)<0)
- {
- //printf("ni še");
- sleep(1);
- }
- read(fd2,buf,512);
- int st2=atoi(buf);
- printf("This is parent :%d\n",st2);
- //printf("Tuki še dela\n");
- return 0;
- }
Add Comment
Please, Sign In to add comment