Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what behavior will result while function returned but command in function is running in background?

Tags:

linux

bash

shell

Consider a shell script like this:

loop()
{
    while true; do
        sleep 10
        return 1
    done &

    return 0
}

loop
exit 0

The while clause is running in background, but function loop() was returned and the script was exited.

The return 1 clause looks like a syntax error, but the console doesn't output any error message infact.

What behavior will result from this return 1 clause?

EDIT:

Every command in script is running in child process(roughly), but my question is focus on return 1 clause. This command should running in a function context, but while it run, the function context was destroyed. So behavior of this return 1 clause is strange and unclear. Any idea?

like image 520
abadcafe Avatar asked Nov 19 '25 15:11

abadcafe


1 Answers

Consider the following

openvas:~$ vi test.sh
loop()
{
    while true; do
        sleep 10
        echo "1" 
        ps -fu openvas
        return 1
    done &

    echo "2"
    ps -fu openvas
    return 0
}

loop

echo "3"
ps -fu openvas
exit 0

Results

openvas:~$ sh test.sh 
2
UID        PID  PPID  C STIME TTY          TIME CMD
openvas     13653 13603  0 16:22 pts/2    00:00:00 sh test.sh
openvas     13654 13653  0 16:22 pts/2    00:00:00 sh test.sh
openvas     13655 13653  0 16:22 pts/2    00:00:00 ps -fu openvas
openvas     13656 13654  0 16:22 pts/2    00:00:00 sleep 10
3
UID        PID  PPID  C STIME TTY          TIME CMD
openvas     13653 13603  0 16:22 pts/2    00:00:00 sh test.sh
openvas     13654 13653  0 16:22 pts/2    00:00:00 sh test.sh
openvas     13656 13654  0 16:22 pts/2    00:00:00 sleep 10
openvas     13657 13653  0 16:22 pts/2    00:00:00 ps -fu openvas
1
UID        PID  PPID  C STIME TTY          TIME CMD
openvas     13654     1  0 16:22 pts/2    00:00:00 sh test.sh
openvas     13658 13654  0 16:23 pts/2    00:00:00 ps -fu openvas

In the first ps output (echo 2), it is evident that when this script is invoked, bash assigns a PID 13653. which in turn assigns 13654 for the while loop. Then sleep command is invoked with a PID 13656 from the parent 13654. ps command is called from the original script itself.

In the second ps output (echo 3), it is following the same pattern.

In the third ps output (echo 1), you can see that PID 13654 has a parent 1 instead of 13653. This shows that init adopts this orphan. Since the parent process had already completed running and exited by the time the child checked for the parent's PID. This has caused the child to be re-parented under init, which has process ID 1.

In your case, the loop is not destroyed (PID 13654) once the script is exited with return 0, and it continues until it encounters return 1 which breaks it.

like image 75
SriniV Avatar answered Nov 22 '25 05:11

SriniV