后台进程输出到Shell变量的输出

后台进程输出到Shell变量的输出,shell,background-process,ksh,output-redirect,Shell,Background Process,Ksh,Output Redirect,我想将命令/脚本输出到变量,但该过程会被触发在后台运行。我尝试了如下操作,但很少有服务器正确运行,我得到了响应。但在少数情况下,我会感到空虚 我试图在后台运行它,因为命令有机会进入挂起状态,我不想挂起父脚本 希望我能尽快得到回复 #!/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&g

我想将命令/脚本输出到变量,但该过程会被触发在后台运行。我尝试了如下操作,但很少有服务器正确运行,我得到了响应。但在少数情况下,我会感到空虚

我试图在后台运行它,因为命令有机会进入挂起状态,我不想挂起父脚本

希望我能尽快得到回复

#!/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"

试着这样做:

#!/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

将您需要的任何消息添加到代码中。平均而言,这将比总是有一个睡眠声明更快地完成。您可以通过使命令
sleep 6
而不是
ls-l

来查看它的功能。我无法在5s后终止当前进程($$),因为还需要根据命令输出触发其他操作。我需要的方法是,result应该有$(ls-l)的输出,如果“ls-l”在任何情况下被挂起,我必须终止该特定命令并继续。