Anonymous pipeline for Python interprocess communication

Source: Internet
Author: User
Tags assert

Anonymous pipeline

A pipeline is a one-way channel, a bit like a shared-memory cache. The pipe has both ends, including inputs and outputs. For a process, it sees only one end of the pipe, either the input or the output.

Os.pipe () returns 2 file descriptors (R, W), which represent both readable and writable. The sample code is as follows:

#!/usr/bin/pythonImportTimeImportOs def child(wpipe):Print' Hello from child ', Os.getpid ()) while True: Msg =' How is you\n '. Encode () Os.write (Wpipe, msg) Time.sleep (1) def parent():Rpipe, wpipe = Os.pipe () pid = Os.fork ()ifPID = =0: Child (Wpipe)assert False,' fork child process error! '    Else: Os.close (wpipe) print (' Hello from parent ', Os.getpid (), pid) Fobj = Os.fdopen (Rpipe,' R ') while True: recv = Os.read (Rpipe, +)PrintRecvparent ()

The output is as follows:

(‘hello from parent‘50535054)(‘hello from child‘5054)how are youhow are youhow are youhow are you

We can also improve the code without Os.read () reading the binary bytes from the pipeline, but rather reading the string from the file object. You need to use Os.fdopen () to wrap the underlying file descriptor (pipe) into a file object, and then use the ReadLine () in the file object. Method read. Note here that the ReadLine () method of the file object always reads a line with a newline character ' \ n ', and even a newline character is read out. The other thing to improve is to close the unused end of the parent and child processes in the pipeline.

#!/usr/bin/pythonImportTimeImportOs def child(wpipe):Print' Hello from child ', Os.getpid ()) while True: Msg =' How is you\n '. Encode () Os.write (Wpipe, msg) Time.sleep (1) def parent():Rpipe, wpipe = Os.pipe () pid = Os.fork ()ifPID = =0: Os.close (rpipe) Child (Wpipe)assert False,' fork child process error! '    Else: Os.close (wpipe) print (' Hello from parent ', Os.getpid (), pid) Fobj = Os.fdopen (Rpipe,' R ') while True: recv = Fobj.readline () [:-1]PrintRecvparent ()

The output is as follows:

(‘hello from parent‘51085109)(‘hello from child‘5109)how are youhow are youhow are you

If you want to communicate with the child process in two-way, only one pipe pipe is not enough, need 2 pipe pipe to line. The following example creates a new 2 pipeline in the parent process and then fork the child process. OS.DUP2 () Implements redirection of output and input. The Spawn function is similar to Subprocess.popen (), which can send a message to a child process, which can retrieve the returned data from the child process.
?

#!/usr/bin/python#coding =utf-8ImportOS, sys def spawn(Prog, *args):STDINFD = Sys.stdin.fileno () stdoutfd = Sys.stdout.fileno () parentstdin, childstdout = Os.pipe () Childstdin, pare ntstdout= os.pipe () pid = Os.fork ()ifPid:os.close (Childstdin) os.close (childstdout) os.dup2 (Parentstdin, STDINFD)#输入流绑定到管道, redirect the input to the pipe end ParentstdinOs.dup2 (Parentstdout, STDOUTFD)#输出流绑定到管道, send to child process Childstdin    Else: Os.close (Parentstdin) os.close (parentstdout) os.dup2 (Childstdin, STDINFD)#输入流绑定到管道Os.dup2 (Childstdout, stdoutfd) args = (prog,) + args OS.EXECVP (prog, args)assert False,' EXECVP failed! 'if__name__ = =' __main__ ': Mypid = Os.getpid () spawn (' python ',' pipetest.py ',' spam ')Print ' Hello 1 from parent ', Mypid#打印到输出流parentStdout, piped to child process ChildstdinSys.stdout.flush () Reply = Raw_input () sys.stderr.write (' Parent got: '%s ' \ n '% reply)#stderr没有绑定到管道上    Print ' Hello 2 from parent ', Mypid sys.stdout.flush () Reply = Sys.stdin.readline ()#另外一种方式获得子进程返回信息Sys.stderr.write (' Parent got: '%s ' \ n '% reply[:-1])

The pipetest.py code is as follows:

#coding =utf-8Import OS, Time, Sysmypid = Os.getpid () Parentpid = Os.getppid () sys.stderr.Write(' child%d of%d got arg: '%s ' \ n ' %(Mypid, Parentpid, sys.argv[1])) forI in range (2): Time.Sleep(3)recv= Raw_input ()#从管道获取数据, from the father often stdout     Time.Sleep(3)Send=' child%d Got: [%s] '% (Mypid,recv)Print(Send)#stdout绑定到管道上, send to Parent process stdinSys.stdout.flush ()

Output:

72657264"spam"Parent"Child 7265 got: [Hello 1 from parent 7264]"Parent"Child 7265 got: [Hello 2 from parent 7264]"

Anonymous pipeline for Python interprocess communication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.