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.

  • 1
    What sort of lock do you want to place on the file? – JdeBP Feb 27 '18 at 21:01
  • 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 1 '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 1 '18 at 16:32

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.

  • Thanks, using the perl example I'm able to lock a file and reproduce the error. – Off The Gold Mar 1 '18 at 15:00
  • flock is available as a standalone command. – Patrick Mevzek Mar 16 '18 at 4:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.