ogs
ogs

Reputation: 1239

Bash store command PID in variable and kill process

I would like to use a shell script in order to establish ethernet connection.

I am using a function implemented as :

function connec()
{
    ip link set eth0 up
    sleep 5
    udhcpc -i eth0
    pid=$$
    echo $pid
    ps 
    kill -9 $pid
}

However, the script returns :

743
743 root      2704 S    {script.sh} /bin/bash ./script.sh connect
767 root      2200 S    udhcpc -i eth0
Killed

I don't succeed in store 767 rather than 743. I also tried by using $! but in that specific case "echo $pid" returns 0.

Upvotes: 5

Views: 17988

Answers (1)

paxdiablo
paxdiablo

Reputation: 882626

$$ is the current process which means the script is killing itself. You can get the process ID of the last process you started in the background, with $! but it appears you're not actually starting one of those.

With your code segment:

udhcpc -i eth0
pid=$$

the pid= line will only be executed when udhcpc exits (or daemonises itself, in which case neither $$ nor $! will work anyway), so there's zero point in trying to kill of the process.

To run it in the background and store its process ID, so you can continue to run in the parent, you could use something like:

udhcpc -f -i eth0 &
pid=$!

and you're using -f to run in foreground in that case, since you're taking over the normal job control.

Or, alternatively, since udhcpc can create its own PID file, you can use something like:

udhcpc -i eth0 -p /tmp/udhcpc.eth0.pid
pid=$(cat /tmp/udhcpc.eth0.pid)

Upvotes: 9

Related Questions