【问题标题】:Output of background process output to Shell variable后台进程输出到 Shell 变量的输出
【发布时间】:2015-10-30 00:29:39
【问题描述】:

我想将命令/脚本的输出输出到变量,但进程被触发在后台运行。我尝试如下,很少有服务器正确运行它,我得到了响应。但在少数情况下,我将 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"

【问题讨论】:

    标签: shell background-process ksh output-redirect


    【解决方案1】:

    试试这样的:

    #!/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 语句完成得快得多。你可以通过命令sleep 6而不是ls -l来查看它的作用

    【讨论】:

    • 我无法在 5 秒后终止当前进程($$),因为根据命令输出还需要触发其他操作。我需要的方式是,结果应该有 $(ls -l) 的输出,如果“ls -l”在任何情况下都挂起,我必须终止该特定命令并继续。
    猜你喜欢
    • 1970-01-01
    • 2015-10-03
    • 2015-05-30
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多