Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In the code snippet below, I want the script to be limited to only running one copy at a time, and for it to restart server.x if it dies for any reason.

Without flock involved, the loop correctly restarts if I kill the server process, but once I use flock to ensure the script is only running once, if I kill server.x it also kills the parent process.

How can I ensure that killing the child process in a flock script keeps the parent around?

set -e
    flock -x -n 200
    while true
        ./server.x $1
) 200>/var/lock/.m_rst.$1.lock
share|improve this question
I would suggest getting rid of set -e and doing proper error handling. – Dennis Williamson Feb 7 '11 at 6:53
up vote 0 down vote accepted

I think that the lock file might be bothering the subprocess, causing it to terminate with a non-zero exit status: set -e will cause your script to terminate if one of the commands inside exit non zero for example:

set -e
echo hello
echo goodbye



It's also worth noting that the flock(2) manpage indicates that the flock system call will copy the file handle to forked processes and across execve; this might mean that server.x is unhappy having the lock file open. In the following example the lock will be held by both processes:

  flock -x -n 200
) 200>/tmp/test.lock

Executing this test while performing lsof | grep /tmp/test.lock will show the lockfile is opened by both processes.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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