Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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?

#!/bin/bash
set -e
(
    flock -x -n 200
    while true
    do
        ./server.x $1
    done
) 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

1 Answer 1

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:

#!/bin/bash
set -e
echo hello
false
echo goodbye

Outputs:

hello

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:

#!/bin/bash
(
  flock -x -n 200
  bash
) 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

 
discard

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.