I use fcntl()
for file capture and then I call execlp()
to open file by nano. I run the program here and in another session. Process from new session also open the file by nano, but it should be waiting for unlock. Effect is same for mandatory and advisory lock.
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define editor "nano"
int main(int argc, char *argv[]) {
struct flock lock;
int fd;
if ((fd = open(argv[1], O_RDWR)) == -1) {
perror("Cannot open file");
exit(EXIT_FAILURE);
}
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
if (fcntl(fd, F_SETLKW, &lock) == -1) {
perror("fcntl failed");
exit(EXIT_FAILURE);
}
execlp(editor, editor, argv[1], NULL);
perror("exec is not working");
exit(EXIT_FAILURE);
}
Man: The new process also inherits the following attributes from the calling process: ... file-locks (see fcntl(2) and lockf(3C))
How is it possible?