来查看它的作用。
我想得到一个命令/脚本的输出到一个变量,但进程被触发在后台运行。我尝试如下,几个服务器正确运行它,我得到了响应。但在少数情况下,我得到i_res为空。
我试图在后台运行它,因为命令有机会进入挂起状态,我不想挂起父脚本。
希望我能尽快得到答复。
#!/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