Search code examples
python-3.xshellexecvp

Missing output after execvp on Ubuntu 22?


I have a short Python code (main.py):

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

When I run it I can see the terminal output of os.getpid() and os.execvp commands, but no print("hello").

However when I have another file (another.py) with the content of:

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

And then change main.py to be:

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

Then I can see the output of os.getpid() and print("hello")

What is the idea behind execvp?


Solution

  • A very simple script that illustrates fork exec and wait

    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')