gpt4 book ai didi

linux - bash 中的奇怪行为(可能还有其他 shell?)

转载 作者:IT王子 更新时间:2023-10-29 00:54:34 26 4
gpt4 key购买 nike

当我这样做时:

/bin/bash -c 'cat /proc/$$/cmdline'

我得到的输出是:

cat/proc/25050/cmdline

而我预期的输出是:

/bin/bash -c 'cat /proc/$$/cmdline'

另一方面,当我这样做时:

/bin/bash -c 'echo $$; cat /proc/$$/cmdline'

我得到了预期的输出,即:

28259
/bin/bash-cecho $$; cat /proc/$$/cmdline

似乎 $$ 是 cat 的 pid 而不是 bash/sh 的 pid。
这是为什么?
shell 是否进行某种解析和 execve() 样式替换?如果是这样,它如何在替换之前就知道猫的 PID?

最佳答案

为了理解这种行为,必须弄清楚 bash 如何执行在命令行上传递给它的命令。关键是如果命令足够简单,就没有fork(或clone 或类似的东西)。

$ strace -f -e clone,execve /bin/bash -c 'cat /proc/$$/cmdline'
execve("/bin/bash", ["/bin/bash", "-c", "cat /proc/$$/cmdline"], [/* 80 vars */]) = 0
execve("/bin/cat", ["cat", "/proc/2942/cmdline"], [/* 80 vars */]) = 0
cat/proc/2942/cmdline+++ exited with 0 +++
$

OTOH 如果命令更复杂,bash 分支:

$ strace -f -e clone,execve /bin/bash -c 'echo $$; cat /proc/$$/cmdline'
execve("/bin/bash", ["/bin/bash", "-c", "echo $$; cat /proc/$$/cmdline"], [/* 80 vars */]) = 0
2933
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7ff64e6779d0) = 2934
Process 2934 attached
[pid 2934] execve("/bin/cat", ["cat", "/proc/2933/cmdline"], [/* 80 vars */]) = 0
/bin/bash-cecho $$; cat /proc/$$/cmdline[pid 2934] +++ exited with 0 +++
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=2934, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---
+++ exited with 0 +++
$

It seems like $$ is cat's pid rather than bash/sh's pid.

实际上两者兼而有之。 bash execve s cat 直接,所以一个变成另一个。

要了解不 fork 行为到底需要什么,我们需要查看源代码。有这样的评论:

      /*
* IF
* we were invoked as `bash -c' (startup_state == 2) AND
* parse_and_execute has not been called recursively AND
* we're not running a trap AND
* we have parsed the full command (string == '\0') AND
* we're not going to run the exit trap AND
* we have a simple command without redirections AND
* the command is not being timed AND
* the command's return status is not being inverted
* THEN
* tell the execution code that we don't need to fork
*/

Source

关于linux - bash 中的奇怪行为(可能还有其他 shell?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39332389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com