当 %x 与单个参数一起使用时(就像您正在做的那样),Ruby 执行 shell 扩展。
这是我对发生了什么的猜测:
Ruby scans the command to determine if there are any special characters that would result in the need to perform shell expansion, if so it calls the shell to do that. In the second example the single quotes are enough to make Ruby want to call the shell to do the expansion, hence the fork. In the first example Ruby can determine that shell expansion is not needed as the command contains no special characters (after variable expansion), hence no fork. The difference between the two versions probably has to do with an internal change in how ruby tries to determine is shell expansion is needed. I get a fork for the second example on ruby 1.8.5 on a 32-bit machine.
[EDIT]
Okay, I took a look at the source code for ruby 1.8.4 and 1.8.6 and both versions use the same criteria to determine whether or not to call a shell to perform shell expansion, if any of the following characters exist in the command line the shell will be invoked when one argument to %x is provided:
*?{}[]<>()~&|\\$;'`"\n
Ruby is actually calling the shell in both cases (in example that contains the quotes), the reason you are seeing different outputs from pstree
is due to differences in the the sh
command on the different machines, one calls fork
, the other doesn't. To see this for yourself, run this command on both machines:
/bin/sh -c "pstree $$"
This is the command that Ruby is using to execute pstree
in the example with quotes on both machines. You should see bash---pstree
on the 32-bit machine and bash---sh---pstree
on the other one.
So now I'm curious, what led you to discover this difference and is it causing a problem?