我在脚本中使用 os.system() 来调用 shell 命令。我写了一个示例脚本来了解 os.system() 如何执行命令。
import os
os.system("sleep 20")
我在 freeBSD 和 linux 机器上运行上面的代码然后执行 ps aux | grep sleep
,结果如下:
FreeBSD:
:~]# ps aux | grep sleep
root 94832 0.0 0.0 2768 984 0 S+ 5:31AM 0:00.00 sleep 20
Linux(Ubuntu):
root 32726 0.0 0.0 4440 648 pts/2 S+ 01:01 0:00 sh -c sleep 20
root 32727 0.0 0.0 7192 612 pts/2 S+ 01:01 0:00 sleep 20
两台机器上的 Shell 都是 bash。
因为 os.system(cmd)
在子 shell 中执行 cmd
,所以不应该有 sh -c sleep 20
进程在运行在 freeBSD 上也是如此吗?有人可以解释这种行为吗?
最佳答案
"sh"在 Linux 和 FreeBSD 上不一样。 Linux 的/bin/sh 进行 fork() 调用,但 FreeBSD 的/bin/sh 进行 execve() 调用来执行命令,因此它不会产生 Linux 中显示的新进程。
Linux:
sh-4.1$ sh --version
sh --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
自由系统:
man sh
DESCRIPTION
The sh utility is the standard command interpreter for the system. The
current version of sh is close to the IEEE Std 1003.1 (“POSIX.1”)
specification for the shell. It only supports features designated by
POSIX, plus a few Berkeley extensions. This man page is not intended to
be a tutorial nor a complete specification of the shell
HISTORY
A sh command, the Thompson shell, appeared in Version 1 AT&T UNIX. It was
superseded in Version 7 AT&T UNIX by the Bourne shell, which inherited the
name sh.
This version of sh was rewritten in 1989 under the BSD license after the
Bourne shell from AT&T System V Release 4 UNIX.
AUTHORS
This version of sh was originally written by Kenneth Almquist.
关于Python:了解 os.system 在 linux 和 freeBSD 上的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39684321/