Setting variables in a KSH spawned process

泄露秘密 提交于 2020-01-04 16:57:50

问题


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?


回答1:


You can get the whole process' output using command substitution, like:

VAR1=$(somecommand &)
VAR2=$(somecommand &)
...
wait
echo $VAR1 $VAR2



回答2:


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

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

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

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

and here is the parent script:

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

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.



来源:https://stackoverflow.com/questions/13298541/setting-variables-in-a-ksh-spawned-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!