Python:了解 os.system 在 linux 和 freeBSD 上的行为

Python: Understanding the behaviour of os.system on linux and freeBSD

我在脚本中使用 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,在 freeBSD 上不应该有一个 sh -c sleep 20 进程 运行 吗?有人可以解释一下这种行为吗?

"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.

FreeBSD:

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.