Outputting the output of a background process to a Shell variable

I want to get the command / script result for a variable, but the process is running in the background. I tried as below and multiple servers worked correctly and I got a response. But in few, I get i_res as empty.

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

Hope I get an answer 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"

      

+3


source to share


1 answer


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 all the codes you need. On average, this will complete much faster than always with sleep expression. You can see what it does by running the command sleep 6

insteadls -l

+1


source







All Articles