Hello danielt,
Thanks for the reply
I mean I’m not able to understand how " lockf c function " works. I read many documentations and test many c programs using it, but the behavior is not what i was thinking about.
In my head, after reading documentation in the website http://manpagesfr.free.fr/man/man3/lockf.3.html, and this site: https://www.editions-eni.fr/open/mediabook.aspx?idR=85a96ece19e334d9c274518d81a49e08,
I thought it was enough to just set a lock with F_TLOCK or F_LOCK mode with a c program (for example Lockfile.c), and then use F_TEST mode in an other program in c (isLock.c) would just have to check for that lock, but that sounds more complicated than that.
I tried this code to lock a file:
---------------- Lockfile.c ------------------
#include <stdlib.h> /* for exit() /
#include <stdio.h> / for perror() /
#include <unistd.h> / for lockf(), lseek() /
#include <fcntl.h> / for open() */
int main(int argc, char *argv) {
/ open file: we need O_RDWR for lockf */
int fd = open("/dev/ttyuart0", O_RDWR);
if (fd == -1) {
perror(“open”);
exit(EXIT_FAILURE);
}
if (lockf(fd, F_LOCK, 0) == -1) {
perror(“lockf(LOCK)”);
exit(EXIT_FAILURE);
}else{
printf(“file /dev/ttyuart0 locked\n”);
}
}
and this code to verify that the file is locked:
---------------- isLocked.c -------------------
#include <stdlib.h> /* for exit() /
#include <stdio.h> / for perror() /
#include <unistd.h> / for lockf(), lseek() /
#include <fcntl.h> / for open() */
int main (int argc , char *argv[]) {
int fd;
fd = open("/dev/ttyuart0", O_RDWR);
if(lockf (fd, F_TEST, 0) < 0){
printf (“File /dev/ttyuart0 is locked\n”);
}else{
printf(“File /dev/ttyuart0 is unlocked\n”);
}
close(fd);
}
The cross compile for my board is ok without error or warnings.
When I use the script Lockfile, I have the message “file /dev/ttyuart0 locked”, that is the expected, behaviour, but after that, when I execute the isLocked script, I have the message: “File /dev/ttyuart0 is unlocked”. That’s weird because I lock it with the first script before. Furthermore, when I execute twice the script Lockfile, the second time, I have the response: “file /dev/ttyuart0 locked”, that’s weird because as it is already lock, I expected it to return an error but that not the case.
Both scripts are following executed. Maybe to solve my problem I need something other than lockf statement, but I don’t know what.
Here is an exemple of execution:
root@pc:~# ./ Lockfile
file /dev/ttyuart0 locked
root@pc:~# ./ isLocked
File /dev/ttyuart0 is unlocked
root@pc:~# ./ Lockfile
file /dev/ttyuart0 locked
root@pc:~# ./ Lockfile
file /dev/ttyuart0 locked
root@pc:~# ./ isLocked
File /dev/ttyuart0 is unlocked
If you have an idea about what’s I’m doing wrong or conceived wrong about the behaviour of lockf, thanks in advance. Have you got an idea about how to really lock and test locking file with two different scripts.
best reguards.