9

I have a process which has been spawned from a shell. It is running as a background process and exporting a DB to a CSV file in /tmp.

How can I tell when the background process has completed (finished / quit) or if the CSV file lock has closed? I plan to FTP the file to another host once it's written, but I need the complete file before I start the file transfer.

7

On Linux, the file is not locked even when a program is writing to it (unlike windows).

To check if the process is completed, use:

while [[ 1 ]]; do
  pgrep dbprocess &>/dev/null

  if [[ $? -eq 0 ]]; then
    echo still running
  else
    echo finished
    # start ftp transfer
  fi
  sleep 2
done

To check if the process has the file open, you can use

  • lsof <file> it will list the processes which opened <file>

  • ls -l /proc/$(pgrep db-process)/fd lists the file descriptors open by the process db-process

| improve this answer | |
7

You can use the wait shell built-in to accomplish this.

The wait builtin simply causes the shell to pause waiting for background jobs to complete. You can either pass it a specific job to wait for, or have it wait for all jobs.

For example:

echo $(date): starting
sleep 5 &
echo $(date): do something else
wait
echo $(date): background job finished

Which results in:

Thu Sep 25 12:06:48 EDT 2014: starting
Thu Sep 25 12:06:48 EDT 2014: do something else
Thu Sep 25 12:06:53 EDT 2014: background job finished
| improve this answer | |

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.