简体   繁体   中英

Bash forking a subshell

I have a bash script in which I want to run some unrelated commands in a forked processes. These commands should only run in the forked process, while other commands should only run in the parent.

echo "I am parent statement 1"
( echo "I am child statement 1"; echo "I am child statement 2"; sleep 30) &
echo "I am parent statement 2"

In this example will the parent shell only output the 'parent' statements, and the child only echo the 'child statements'? Or will the child echo parent statement 2 upon return?

As well, will the parent will wait for the child (doing a sleep 30)? Or will the parent exit and the child keep running for 30 seconds?

Each process will only run its own statements.

If you modify your script slightly, you can do an experiment which shows that the child outlives the parent.

#!/bin/bash

echo "I am parent statement 1"
( echo "I am child statement 1"; echo "I am child statement 2"; sleep 30) &
jobs -l
echo "I am parent statement 2"
echo $$

If you run the script and then do ps aux | grep <pid> ps aux | grep <pid> for both the parent and child, you'll see that the parent has died while the child lives on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM