Lock a file in bash using flock and lockfile

后端 未结 1 1427
-上瘾入骨i
-上瘾入骨i 2021-01-07 05:59

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

相关标签:
1条回答
  • 2021-01-07 06:56

    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:

    • The file descriptor used to grab the lock is in append mode (when writing to the end), or in read mode (when reading), so you aren't overwriting the file before you even grab the lock.
    • We're running the 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).
    0 讨论(0)
提交回复
热议问题