script called once but turns two processes

Asked

Viewed 41 times

0

I have here a script to test a function in the background.

When I spin is launched two processes and I do not understand why.

One stops at the "Sleep 20", and the other wheel eternally.

#!/bin/bash

back(){
    n=0
    while [ 1 ]
    do      
        echo $n
        n=$(($n+1))
        sleep 5
    done
}

back &
sleep 20
exit

command "ps -a" on call:

 PID    TTY      TIME      CMD
 8964   pts/2    00:00:00  backgroundteste
 8965   pts/2    00:00:00  backgroundteste
 8966   pts/2    00:00:00  sleep
 8982   pts/2    00:00:00  sleep

after the "Sleep 20":

PID    TTY      TIME      CMD
8965   pts/2    00:00:00  backgroundteste
9268   pts/2    00:00:00  sleep

then forget about...

Because?

1 answer

2


This command

back &

creates a process in the background.

Even after the original script has finished a copy of it is running in the background, because of the "&" above.

  • But a call to "backgroudteste" created two "backgroundteste" processes. The "backgroundteste" script does not call itself for this to happen.

  • The original script stays on the air for 20 seconds after calling the "back" function in the background. In these 20 seconds there will be the two "backgroundtest" processes. After 20 seconds the initial script ends, but the background process continues forever because of the "while [ 1 ]" infinite loop. The "back" function is "tied" in the script, because it is a function created within the script, so in ps what appears is the "backgroundtest". (In fact each "backgroundtest" process is an instance of bash interpreting the script.)

  • I get it. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.