Search code examples
shellsubprocesssubshell

How shell executes this code 'cd $dir && php -f test_loop.php &'


I wonder how shell executes this code in .sh file(like test.sh):

while true
do
    # check php process. If not running, run it. 
    cd $some_dir && php -f some_file.php &
    # sleep 1s
done

Some output:

ps -ef|grep test|grep -v grep
root     10963  3040  0 11:13 pts/19   00:00:00 /bin/bash ./test.sh start
root     10973 10963  0 11:13 pts/19   00:00:00 /bin/bash ./test.sh start
root     10975 10973  0 11:13 pts/19   00:00:00 php -f test_loop.php

In my case, there are three processes, including 2 test.sh and 1 php. But if use the following code, that is, in two lines or parentheses, it's ok:

cd $some_dir && (php -f some_file.php &)

or

cd $some_dir
php -f some_file.php &

output:

ps -ef|grep test|grep -v grep
root     11112  3040  0 11:14 pts/19   00:00:00 /bin/bash ./test.sh start
root     11122 11112  0 11:14 pts/19   00:00:00 php -f test_loop.php

In this case, two kinds of codes are executed in a subshell, which is what we expect.

In the first case, it seems that there is an intermediate process between the original process and php process. So what's it and why is it created?


Solution

  • The statement

    cd $some_dir && php -f some_file.php &
    

    runs in a subshell and that's the reason you see an extra process. In your output, PID 10963 is the original (parent) shell and 10973 is the subshell whose child is the PHP process. The grandparent (PID 10963) is active because of the infinite loop.

    When you remove &&, the two statements run in the parent shell itself and hence you don't see the extra process.