Background spawned process in Expect

I had the same problem and figured this out.

When expect exits, it sends a SIGHUP (hangup signal) to the spawned subprocess. By default, this SIGHUP causes termination of the spawned process.

If you want the underlying process not to die from SIGHUP you have two easy options. Both work well:

1) Ask expect to make the underlying process ignore SIGHUP in the spawn line like this:

#!/usr/bin/expect -f
...
spawn -ignore HUP command args...
...
expect_background

2) Do it yourself - ignore SIGHUP in the underlying process itself:

Here's working script demonstrating method 2:

#!/usr/bin/expect -f
#
# start a process and background it after it reaches a certain stage
#
spawn perl -e "\$SIG{HUP} = 'IGNORE'; for (\$a='A';; \$a++) {print qq/value is \$a\\n/; sleep 1;}"

set timeout 600

# Detailed log so we can debug (uncomment to enable)
# exp_internal -f /tmp/expect.log 0

# wait till the subprocess gets to "G"
expect -ex "value is G"

send_user "\n>>> expect: got G\n"

# when we get to G, background the process
expect_background

send_user ">>> spawned process backgrounding successful\n"
exit 0

Here's a running example:

$ ./expect-bg
spawn perl -e $SIG{HUP} = 'IGNORE'; for ($a='A';; $a++) {print qq/value is $a\n/; sleep 1;}
value is A
value is B
value is C
value is D
value is E
value is F
value is G

>>> expect: got G
>>> spawned process backgrounding successful

And as expected in ps output, the perl process is backgrounded and alive.

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
hankm     6700  0.0  0.0  17696  2984 ?        Ss   18:49   0:00 perl -e $SIG{HUP} = 'IGNORE'; for ($a='A';; $a++) {print qq/value is $a\n/; sleep 1;}