在KSH产生过程中设置变量 [英] Setting variables in a KSH spawned process

查看:79
本文介绍了在KSH产生过程中设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个冗长的菜单脚本,该脚本脚本依赖于一些变量的命令输出.这些命令每个都需要花费几秒钟来运行,我想产生新的过程来设置这些变量.看起来像这样:

I have a lengthy menu script that relies on a few command outputs for it's variables. These commands take several seconds to run each and I would like to spawn new processes to set these variables. It would look something like this:

VAR1=`somecommand` &
VAR2=`somecommand` &
...
wait
echo $VAR1 $VAR2

问题是进程被生成并因设置的变量而死亡.我意识到我可以通过将它们发送到一个文件然后读取该文件来做到这一点,但是我想在没有临时文件的情况下做到这一点.有什么想法吗?

The problem is that the processes are spawned and die with those variables they set. I realize that I can do this by sending these to a file and then reading that but I would like to do it without a temp file. Any ideas?

推荐答案

这很笨拙,但对我有用.我有三个脚本.

This is rather clunky, but works for me. I have three scripts.

cmd.sh是您的"somecommand",它只是一个测试脚本:

cmd.sh is your "somecommand", it is a test script only:

#!/bin/ksh
sleep 10
echo "End of job $1"

下面是wrapper.sh,它运行一个命令,捕获输出,完成后向父级发送信号,然后将结果写入stdout:

Below is wrapper.sh, which runs a single command, captures the output, signals the parent when done, then writes the result to stdout:

#!/bin/ksh
sig=$1
shift
var=$($@)
kill -$sig $PPID
echo $var

这是父脚本:

#!/bin/ksh

trap "read -u3 out1" SIGUSR1
trap "read -p out2" SIGUSR2

./wrapper.sh SIGUSR1 ./cmd.sh one |&
exec 3<&p
exec 4>&p

./wrapper.sh SIGUSR2 ./cmd.sh two |&
wait
wait
echo "out1: $out1, out2: $out2"
echo "Ended"

2x等待,因为第一个将被中断.

2x wait because the first will be interrupted.

在父脚本中,我两次运行包装程序,对于每个作业一次,传递要运行的命令和任何参数. |&的意思是管道到后台"-作为协同进程运行.

In the parent script I am running the wrapper twice, once for each job, passing in the command to be run and any arguments. The |& means "pipe to background" - run as a co-process.

这两个exec命令将管道文件描述符复制到fds 3和4.作业完成后,包装器向主进程发出信号以读取管道.使用trap捕获信号,该信号读取相应子进程的管道,并收集结果数据.

The two exec commands copy the pipe file descriptors to fds 3 and 4. When the jobs are finished, the wrapper signals the main process to read the pipes. The signals are caught using the trap, which read the pipe for the appropriate child process, and gather the resulting data.

复杂而笨拙,但似乎可以正常工作.

Rather convoluted and clunky, but it appears to work.

这篇关于在KSH产生过程中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆