0

I currently have the following code whereby I am using os.execv() to execute some sort of process. For example:

process_param = [exec_path, f]
pid = os.fork(                      
try:
   if (pid > 0):
      #parent 
      time_lim = 55
      for _ in range(time_lim):
         child_pid, status = os.waitpid(-1, os.WNOHANG)

         if (child_pid != 0):
            break

         time.sleep(1)
        
   elif (pid == 0):
      os.execv(exec_path, process_param)
   else:
      status = 1
except ChildProcessError:
   status = 1

Before you tell me to use subprocess, please note that (for assignment purposes), I should stick to this particular method of running bash commands through Python.

I would like to do something similar to this:

var_a=`cat some_file`

Does anyone know how I can capture the output derived from the os.execv() command (located in the child process) and store it in a variable (perhaps returning it to the parent process)?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • You will need to connect the standard output filehandle of the new process to something in the parent process which reads it. As you note, `subprocess` already does this for you - perhaps look at its implementation for an example. – tripleee Nov 08 '20 at 13:53
  • I was recommended that I use os.pipe(). However, I'm not sure I understand its implementations. – knuckles the man Nov 08 '20 at 13:58
  • It oughtn't be hard to find an exposition of how this is done in C on Unix-like systems; mapping the constructs to Python `os.*` calls should then be straightforward. – tripleee Nov 08 '20 at 14:03

1 Answers1

1

Using os.pipe and os.dup2. You can learn more from https://docs.python.org/3/library/os.html#os.dup2.

import os
import sys

r, w = os.pipe()
pid = os.fork()
if pid:
    # parent
    os.close(w)
    r = os.fdopen(r)
    print(r.read())
    sys.exit(0)
else:
    # child
    os.close(r)
    # duplicate stdout and stderr to parent
    os.dup2(w, 1)
    os.dup2(w, 2)
    os.execv('/usr/bin/ls', ['-l'])
    sys.exit(0)
eshizhan
  • 4,235
  • 2
  • 23
  • 23