• IPC-->PIPO


    Programing python 4th page 228

     1 """
     2 IPC
     3 http://www.cnblogs.com/BoyXiao/archive/2011/01/01/1923828.html
     4 """
     5 import os,time
     6 import threading
     7 
     8 def child(pipeout):
     9     zzz = 0
    10     while True:
    11         time.sleep(zzz)                                             # make parent wait
    12         msg=('spam %03d 
    ' % zzz).encode()                         # pipes are binary bytes
    13         os.write(pipeout,msg)                                       # send to parent
    14         zzz = (zzz+1)%5
    15         
    16 def parent(pipein):
    17     while True:
    18         line = os.read(pipein,32)                                   # blocks until data sent
    19         print('parent %d got [%s]  at [%s]'%(os.getpid(),line,time.ctime()))
    20     
    21 pipein,pipeout = os.pipe()
    22 threading.Thread(target = child,args=(pipeout,)).start()
    23 parent(pipein)
    View Code

    2.Bidirectional IPC

     1 """
     2 location: programing python 4td page 229
     3 spawn a child process/program,connect my stdin/stdput to child process's stdout/stdin 
     4 my reads and writes map to output and input streams of the spawn program;much like typing
     5  together streams with subprocess module
     6 """
     7 import  os,sys
     8 def spawn(prog,*args):
     9     stdinFd = sys.stdin.fileno()            #pass progname,cmdline args
    10     stdoutFd =sys.stdin.fileno()            # get desciptors for streams,normally stdin =0,stdout =1
    11     
    12     parentStdin,childStdout = os.pipe()     # make two IPC pipe changels
    13     childStdin,parentStdout = os.pipe()     # pipe returns(inputfd,outputfd)
    14     pid = os.fork()                         #make a copy of this process
    15     if pid:
    16         os.close(childStdout)               # in parent process after fork
    17         os.close(childStdin)                # close child ends in parent
    18         os.dump2(parentStdin,stdinFd)       # my sys.stdin copy = pipe1[0]
    19         os.dump2(parentStdout,stdoutFd)     # my sys.stdout copy = pipe2[1]
    20     else:
    21         os.close(parentStdin)               # in child process afte fork:
    22         os.close(parentStdout)              # close parent ends in child
    23         os.dump2(childStdin,stdinFd)        # my sys.stdin copy = pipe2[0]
    24         os.dump2(childStdout,stdoutFd)      # my sysout copu = pipe1[1]
    25         args = (prog,)+args
    26         os.execvo(prog,args)                # new program in this process
    27         assert False,'execvp failed'        # os.exec call never returns here
    28     
    29 if __name__=='__main__':
    30     mypid = os.getpid()
    31     spawn('python','pipes-testchild.py','spawm') # fork child program
    32     
    33     print('hello  1 from parent',mypid)      # to child's stdin
    34     
    35     sys.stdout.flush()                       # subvert stdio buffering
    36     reply = input()                          # from child's stdout
    37     sys.stderr.write('parent got: "%s"
    ' % reply) # stderr not tied to pipe
    38     
    39     print('hello 2 from parent',mypid)
    40     sys.stdout.flush()
    41     reply = sys.stdin.readline()
    42     sys.stderr.write('parent got:"%s"
    ' % reply[:-1])
    43     
    View Code

     3.Named Pipes(Fifos)pages 234

    Create a long-lived pipe that exists as a real named file in the filesystem. such files are called named pipes(or sometime,fifos). 

    虽然其是任意程序之外的,但是和计算机中真实文件有关,不依赖被其他任务所共享的内存。因此可以用于线程,进程和独立程序的IPC机制。一旦命名管道文件创建,客户端可以通过名字打开并使用正常的文件操作进行读写。其是单向流。典型的操作是,服务器程序从fifos读数据,客户端程序写数据。另外,2个fifos集可以用于实现双向通信,和匿名通信所做的一样。fifos不支持远程网络连接。

     1 """
     2 name pipes;os.mkfifo is not available on windown
     3 thare is no reason to fork here ,since fifo file ipes
     4 are external to proceses--shared fds in parent/child processes
     5 are irrelevent;
     6 """
     7 import os,time,sys
     8 fifoname ='/tmp/pipefifo'
     9 def child():
    10     pipeout = os.open(filename,os.O_WRONLY)                 # open fifo pipe as fd
    11     zzz = 0
    12     while True:
    13         time.sleep(zzz)
    14         msg =('spam %03d
    ' %zzz).encode()
    15         os.write(pipeout,msg)
    16         zzz =(zzz+1)%5
    17 def parent():
    18     pipein = open(fifoname,'r')                                             # open file as text file object
    19     while True:
    20         line = pipein.readline()[:-1]                                       #block until data sent
    21         print('parent %d got "%s" at %s' % (os.getpid(),line,time.ctime()))
    22 
    23 if __name__ =='__main__':
    24     if not os.path.exits(filename):
    25         os.mkfifo(fifename)                                                 #create a named pipe file
    26     if len(sys.argv) == 1:
    27         parent()                                                            # run as parent if no args
    28     else:
    29         child()                                                             # else run as child process
    View Code
  • 相关阅读:
    Flutter Platform Channels
    catch socket error
    global position
    aria2 添加任务后一直在等待,不进行下载是什么情况?
    通知
    rename file
    长按弹菜单
    Linux命令行下如何终止当前程序?
    IOWebSocketChannel.connect handle errors
    writeAsBytes writeAsString
  • 原文地址:https://www.cnblogs.com/lxk613/p/4808883.html
Copyright © 2020-2023  润新知