Python: fork, pipe and exec

2019-01-18 16:46发布

I want to execute a program in a python application, it will run in the background but eventually come to the foreground.

A GUI is used to interact with it. But controls are offered via a console on stdin and stdout. I want to be able to control it using my application's GUI, so my first idea was:

  • Fork
  • in the parent, dup2 stdin and stdout in order to access them
  • exec the child

Is this easily implementable in python and how? Are there alternative ways to achieve what I want, what would that be?

2条回答
欢心
2楼-- · 2019-01-18 17:37

This is reasonably easy using the standard Python subprocess module:

http://docs.python.org/py3k/library/subprocess.html

查看更多
▲ chillily
3楼-- · 2019-01-18 17:50

That is not much complex in structure to build !

Check this example

if os.fork():
    os._exit(0)
    os.setsid()
    os.chdir("/")
    fd = os.open("/dev/null", os.O_RDWR)
    os.dup2(fd, 0)
    os.dup2(fd, 1)
    os.dup2(fd, 2)
if fd 2:
    os.close(fd)

This python code sets an id, changes the dir, opens a file and process and close !

查看更多
登录 后发表回答