nibs
nibs

Reputation: 31

Output of background process output to Shell variable

I want to get output of a command/script to a variable but the process is triggered to run in background. I tried as below and few servers ran it correctly and I got the response. But in few I am getting i_res as empty.

I am trying to run it in background as the command has chance to get in hang state and I don't want to hung the parent script.

Hope I will get a response soon.

#!/bin/ksh

x_cmd="ls -l"

i_res=$(eval $x_cmd 2>&1 &)

k_pid=$(pgrep -P $$ | head -1)

sleep 5
c_errm="$(kill -0 $k_pid 2>&1 )"; c_prs=$?

if [ $c_prs -eq 0 ]; then

    c_errm=$(kill -9 $k_pid)

fi

wait $k_pid

echo "Result : $i_res"

Upvotes: 3

Views: 1122

Answers (1)

jim mcnamara
jim mcnamara

Reputation: 16399

Try something like this:

#!/bin/ksh


pid=$$                      # parent process
(sleep 5 && kill $pid) &    # this will sleep and wake up after 5 seconds        
                            # and kill off the parent.
termpid=$!                  # remember the timebomb pid
# put the command that can hang here
result=$( ls -l )
                            # if we got here in less than 5 five seconds:
kill $termpid               # kill off the timebomb
echo "$result"              # disply result
exit 0

Add whatever messages you need to the code. On average this will complete much faster than always having a sleep statement. You can see what it does by making the command sleep 6 instead of ls -l

Upvotes: 1

Related Questions