i spent the better part of the day looking for a solution to this problem and i think i am nearing the brink ... What i need to do in bash is: write 1 script that will perio
Let's look at what this does:
flock -x text.txt -c read > text.txt
First, it opens test.txt
for write (and truncates all contents) -- before doing anything else, including calling flock
!
Second, it tells flock
to get an exclusive lock on the file and run the command read
.
However, read
is a shell builtin, not an external command -- so it can't be called by a non-shell process at all, mooting any effect that it might otherwise have had.
Now, let's try using flock
the way the man page suggests using it:
{
flock -x 3 # grab a lock on file descriptor #3
printf "Input to add to file: " # Prompt user
read -r new_input # Read input from user
printf '%s\n' "$new_input" >&3 # Write new content to the FD
} 3>>text.txt # do all this with FD 3 open to text.txt
...and, on the read end:
{
flock -s 3 # wait for a read lock
cat <&3 # read contents of the file from FD 3
} 3<text.txt # all of this with text.txt open to FD 3
You'll notice some differences from what you were trying before:
read
command (which, again, is a shell builtin, and so can only be run directly by the shell) by the shell directly, rather than telling the flock
command to invoke it via the execve
syscall (which is, again, impossible).