ls0f / my-issues

0 stars 0 forks source link

Pipeline #15

Open ls0f opened 8 years ago

ls0f commented 8 years ago

直接引用维基百科

In Unix-like computer operating systems (and, to some extent, Microsoft Windows), a pipeline is a set of processes chained by their standard streams, so that the output of each process (stdout) feeds directly as input (stdin) to the next one. Filter programs are often used in this configuration.

系统通常会提供pipe系统调用。

pipe() creates a pair of file descriptors, pointing to a pipe inode, and places them in the array pointed to by filedes. filedes[0] is for reading, filedes[1] is for writing.

一个简单的程序,使用pipe系统调用。父进程发送当前世界给子进程。

import os
import time
import datetime
import sys

def main():
    pipe = os.pipe()
    pid = os.fork()
    if pid == 0:
        os.close(pipe[1])
        while 1:
            char = os.read(pipe[0], 1)
            if char:
                sys.stdout.write(char)
                sys.stdout.flush()
            else:
                # EOF
                break
        os.close(pipe[0])

    else:
        os.close(pipe[0])
        os.write(pipe[1], str(datetime.datetime.now()))
        os.write(pipe[1], '\n')
        os.close(pipe[1]) # send EOF
        os.wait()

if __name__ == "__main__":
    main()