-2

我有一个有趣的情况。这里的所有代码都是我面临的确切问题的功能性伪代码示例,所以不要开玩笑说分配date. 我实际上想捕获一个更慢、更依赖资源的函数的输出,但date可以很好地显示我遇到的功能障碍。

我正在编写 bash 脚本,我想将进程的输出分配给如下变量:

RESPONSE=$(nice -n 19 date);

现在这给了我RESPONSE一个很好的变量,对吧?好的,如果我想获取内部调用的函数的进程 ID$()怎么办?我该怎么做?我认为这会起作用:

RESPONSE=$(nice -n 19 date & PID=(`jobs -l | awk '{print $2}'`));

这确实给了我变量中的进程 ID PID,但是我不再将输出发送到RESPONSE

我用作功能示例的代码是这样的。这个例子有效,但没有PID;是的,我没有分配 aPID但这是一个例子:

RESPONSE=$(nice -n 19 date);
wait ${PID};
echo "${RESPONSE}";
echo "${PID}"; 

这个例子给了我一个PID但没有RESPONSE

RESPONSE=$(nice -n 19 date & PID=(`jobs -l | awk '{print $2}'`));
wait ${PID};
echo "${RESPONSE}";
echo "${PID}";

任何人都知道我怎样才能获得RESPONSE价值PID

4

1 回答 1

7

Depending on exactly how you set it up, using RESPONSE=$(backgroundcommand) will either wait for the command to complete (in which case it's too late to get its PID), or won't wait for the command to complete (in which case its output won't exist yet, and this can't be assigned to RESPONSE). You're going to have to store the command's output someplace else (like a temporary file), and then collect it when the process finishes:

responsefile=$(mktemp -t response)
nice -n 19 date >$responsefile &
pid=$!
wait $pid
response=$(<$responsefile)
rm $responsefile

(Note that the $(<$responsefile) construct is only available in bash, not in plain posix shells. If you don't start the script with #!/bin/bash, use $(cat $responsefile) instead.)

This still may not do quite what you're looking for, because (at least as far as I can see) what you're looking for doesn't really make sense. The command's PID and output never exist at the same time, so getting both isn't really meaningful. The script I gave above technically gives you both, but the pid is irrelevant (the process has existed) by the time response gets assigned, so while you have the pid at the end, it's meaningless.

于 2013-05-01T03:51:17.727 回答