4

I'd like to use Python's os.execv to replace my current process, but I also want the new process to send stdout to another process (to collect logs and ship them over the network). The process collecting logs also needs to be started by the original Python process.

I'm guessing I need to do some fork, dup2, execv stuff, but I need some help.

In bash, it might look something like this

#!/bin/bash
exec ./foo ∣ ./bar
5
  • 1
    the subprocess module can do this for you: gist.github.com/JacobIRR/dced5ce0f19e4f376aaef19d0e80d9d7 Commented May 19, 2017 at 17:52
  • 1
    @JacobIRR That runs the command in a subprocess, it doesn't replace the current process. Commented May 19, 2017 at 18:12
  • 1
    Minor note, that doesn't quite do what you think it does in Bash - the main process follows the last stage of the pipeline, so the exec has no effect. Commented May 19, 2017 at 19:44
  • @ephemient thanks for the clarification. I guess that means I'm unsure how to do this in both Python and Bash! Commented May 19, 2017 at 19:46
  • 1
    The closest analogue in Bash would be with process substitution such as exec ./foo > >(./bar). Commented May 19, 2017 at 22:54

1 Answer 1

4

You can set up the pipe and processes this way.

import os

(read_fd, write_fd) = os.pipe()
pid = os.fork()
if pid == 0:
    os.dup2(read_fd, 0)
    os.close(read_fd)
    os.close(write_fd)
    os.execlp('./bar', './bar')
    os._exit(-1)  # in case exec fails
os.close(read_fd)
os.dup2(write_fd, 1)
os.close(write_fd)
os.execlp('./foo', './foo')

It's still convenient to use subprocess though, at least for the first part.

import os
import subprocess

p = subprocess.Popen(['./bar'], stdin=subprocess.PIPE)
os.dup2(p.stdin.fileno(), 1)
p.stdin.close()
os.execlp('./foo', './foo')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.