shell 在Ubuntu 22上执行execvp后缺少输出?

uttx8gqw  于 2022-12-19  发布在  Shell
关注(0)|答案(1)|浏览(128)

我有一个简短的Python代码(main.py):

#!/usr/bin/bash                                                                 
import os                                                                       
import subprocess                                                               
print(os.getpid())                                                              
os.execvp("ls", ["ls", "-a"])                                                   
print("hello")

当我运行它时,我可以看到os.getpid()os.execvp命令的终端输出,但看不到print("hello")
然而,当我有另一个文件(another.py)的内容:

#!/usr/bin/bash                                                                                                                 
print("hello")

然后将www.example.com更改main.py为:

#!/usr/bin/bash                                                                 
import os                                                                       
import subprocess                                                               
print(os.getpid())                                                              
os.execvp("python3", ["python3", "another.py"])

然后我可以看到os.getpid()print("hello")的输出
execvp背后的理念是什么?

ruoxqz4g

ruoxqz4g1#

一个非常简单的脚本,用于说明forkexecwait

import os

print('this will run once')

pid = os.fork()
# duplicates the current process after this point

if pid < 0:
    print('error forking')
    exit()

print('this will run twice')

if pid == 0:
    # we are inside child process
    print('hello from child')
    os.execvp("echo", ["echo", "hello from echo"])
    print('this will not run because child process has been completely replaced by echo process')
else:
    os.wait()
    # wait child process to exit
    print('hello from parent')

相关问题