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

标签 shell background-process ksh output-redirect

我想将命令/脚本的输出输出到一个变量,但该进程被触发在后台运行。我尝试如下,很少有服务器正确运行它,我得到了响应。但在少数情况下,我得到的 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 语句更快地完成。您可以通过命令 sleep 6 而不是 ls -l

来查看它的作用

关于shell - 后台进程输出到Shell变量的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31862857/

相关文章:

linux - 如何查找 DNS 服务器和电子邮件服务器的位置

linux - 即使终端位于脚本本身的当前目录,Bash 终端也不允许使用脚本

php - 在 Windows 机器上的 PHP 中长时间运行的后台进程

ksh - 检查 KSH 脚本参数的数量

unix - 如果条件未在 unix ksh 中返回所需的输出 - 返回错误的输出

linux - KSH密码生成器

arrays - 从 bash 输出 bash 引用数组

shell - Learning Shell - 创建一个带有参数的脚本,运行两个单独的 cli 应用程序

windows-8 - 如果在 CPU 和网络限制内,WinRT 后台任务能否长期存在?

android - 如何知道应用程序的后台服务何时被android中的其他 super 访问应用程序阻止