0

I would like to lock a file, run some tests then unlock the file. How can I do this. I could use the command line, perl, or a shell script.

The reason I would like to lock the file is occasionally when connecting with ftp to our Apache server we get an error upon deleting files: "Cannot open or remove a file containing a running program". I would like to test using an ftp move command instead of a delete command to see if I catch this error. I would like to test whether locking a file would cause this error.

Kusalananda
  • 333,661
Off The Gold
  • 195
  • 2
  • 8
  • 1
    What sort of lock do you want to place on the file? – JdeBP Feb 27 '18 at 21:01
  • 1
    Note that if the questioner responds that xe wanted to place one of the fcntl() locks, or the old 0000 permissions lock that people can still be found using today, that other question does not address that at all and this is not a duplicate. And flock is not the sole tool for this in any case. – JdeBP Feb 27 '18 at 22:07
  • 1
    This is a very roundabout way of asking the straightforward question What causes this error when I FTP to my server and how do I overcome it?. Of course, the first request for clarification would then be Are you using AIX on the server? What operating system are you using, if not?. – JdeBP Feb 28 '18 at 20:56
  • Right, JdeBP, that is my basic question, I think the error is being caused by a locked file: perhaps a large file being served by the web server. And yes, the server is using AIX. – Off The Gold Mar 01 '18 at 13:57
  • Now that I can lock the file via Perl, I was able to verify a fix that works: If a locked file is detected, upload a temporary file and rename it to the locked file. While we can't ftp-delete or ftp-put over locked file, we can rename over it. – Off The Gold Mar 01 '18 at 16:32

2 Answers2

1

On the quick: file locking is normally only supported by higher level languages (as far as I know).

For perl examples you can start here https://stackoverflow.com/questions/34920/how-do-i-lock-a-file-in-perl or any of the Perl classics like https://docstore.mik.ua/orelly/perl/cookbook/ch07_12.htm (beware SSL cert issues) or such like.

For shell scripting you have to considerJdeBP's comment: why do you want to lock your file. Depending on your answer you could consider strategies like temporarily changing write permissions on the file, renaming the file and processing the renamed file before changing the file name back, working on a copy and rewriting the original afterwards.

Stefan
  • 229
1

You can use the flock command: flock man file

This is where I learned about it. https://stackoverflow.com/questions/24388009/linux-flock-how-to-just-lock-a-file

This is my script for locking a file named 2.txt for 10 seconds (Minor adapation from the script in the link):

exec 3>2.txt    # open a file handle; this part will always succeed
flock -x 3      # lock the file handle; this part will block
sleep 10
exec 3>&-
Grallen
  • 111