mears11 has asked for the wisdom of the Perl Monks concerning the following question:

I have a perl script that runs completely fine in the foreground, but will either hang or exit when run in background mode (tcsh shell in UNIX). The script calls three other scripts: Script 1: Syncs directory structures from two partitions Script 2: Syncs files within directories Script 3: Called in a loop and processes one or more files. All three made UNIX system calls via backticks. Originally, scripts 1 & 2 were called and had their output gathered via backtick and script 3 was called with open. I thought that it was the backticks that were causing the problems and I was receiving: suspended (tty output) messages, so I replaced the backtick calls to script 1 and 2 with open calls and it seemed to work. Then another user ran the wrapper script, backgrounded it, logged off, and the processes exited before completion (not sure if it was directly after logging off or not). What can I do to help these scripts run in the background? I have a feeling it has to do with reading input from the scripts with the open calls, but I’m not sure.
  • Comment on Script hangs or dies when run in background. Works fine in foreground.

Replies are listed 'Best First'.
Re: Script hangs or dies when run in background. Works fine in foreground.
by Tanktalus (Canon) on Nov 11, 2005 at 03:31 UTC

    Read the documentation for various "background" modules, such as Net::Server, Proc::Daemon, and the like. They will likely be very informative.

    In the meantime, try this test. Run your application with stdin redirected from /dev/null. My bet is that you'll find other problems, but that hanging isn't one of them.

    yourscript.pl < /dev/null &
    Well, that's the Bourne-shell syntax. If you're using tcsh, I'm not sure what it'll look like.

    The issue is that anything running in the "background" needs to not rely on stdin for anything. It shouldn't rely on stdout or stderr, either, but that's somewhat less hard and fast of a rule. Some programs have a "background" mode where they close stdin right away to prevent accidental reads from stdin. Then others have a full daemon mode where they use one of the above modules (or, in other languages, the same concepts) to completely pull themselves away from the session that started them to render themselves immune to this type of problem - including the dying during logout.

Re: Script hangs or dies when run in background. Works fine in foreground.
by chrism01 (Friar) on Nov 11, 2005 at 06:37 UTC
    You may or may not know this, but backgrounding a prog does not totally disconnect it from the terminal session. You need to nohup it to do this, ie
    nohup yourprog &
    in shell terms.