Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <stdlib.h>
- int main() {
- char buffer[256] = "";
- struct flock lock = {F_WRLCK, SEEK_SET, 0, 0, getpid()};//from start (0) 'til end (0) of file
- int opened = open("./forlab4.txt", O_RDWR);
- if (opened != -1) {
- if (fcntl(opened, F_SETLK, &lock) == -1) {
- system("clear");
- 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
- fcntl(opened, F_SETLKW, &lock);
- }
- system("clear");
- printf("\033[9B\033[15C\033[91mFile is successfully locked.\033[39m\n");
- int len;
- len = read(opened, buffer, 255);
- write(1, buffer, len);
- sleep(7);
- fcntl(opened, F_UNLCK, &lock);
- system("clear");
- printf("\033[9B\033[14C\033[91mFile is successfully unlocked.\n");
- close(opened);
- return 0;
- } else {
- system("clear");
- printf("\033[9B\033[17C\033[91mFile can not be opened.\n\033[11CProgram will be terminated shortly.\n");
- }
- printf("\033[39m");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement