简体   繁体   English

Python:os.read和f.read之间的区别是什么

[英]Python:what's the differece between os.read and f.read

import os
from threading import Thread
import time
def handle(fd):
    while True:
        data=raw_input()
        if data:
            print('send',data)
            os.write(fd,data)
r,w=os.pipe()
pid=os.fork()
if pid==0:
    os.close()
    os.dup2(r,0)
    # f=os.fdopen(r,'r')
    print(1)
    while True:
        # data=f.read()
        data=os.read(r,1024)
        if data:
            print('get',data)
else:
    os.close(r)
    t=Thread(target=handle,args=(w,))
    t.setDaemon(True)
    t.start()
    time.sleep(5)
    print('parent exit')
    os._exit(0)

when use os.read,the outputs is: 使用os.read时,输出为:

> 1
> dir
> ('send','dir')
> ('get','dir')
> parent exit

when use f.read: 使用f.read时:

> 1
> dir
> ('send','dir')
> parent exit
> ('get','dir')

Obviously,the subprocess was blocking on f.read() until the write end closed which caused by the parent process' withdrawal.What causes their different behavior?I want to make clear of the operating system's actions after calling f.read and os.read. 显然,子进程在f.read()上一直阻塞,直到由父进程的退出导致写结束关闭为止。是什么原因导致它们的不同行为?我想在调用f.read和os之后弄清操作系统的操作。读。 I would be grateful if you can recommend some blogs to me. 如果您能向我推荐一些博客,我将不胜感激。

os.read is a low-level system function. os.read是低级系统功能。 No decoding, no buffering, it just returns raw bytes up to a given limit. 没有解码,没有缓冲,它只是返回原始字节直到给定的限制。 All other reads are built on the top of this function and may call it repeatedly. 所有其他读取均建立在此函数的顶部,并且可能会反复调用它。 They add some functionality like decoding bytes into strings, splitting text on newlines etc. 它们添加了一些功能,例如将字节解码为字符串,在换行符上分割文本等。

In your program the parent sends data and after 5 seconds closes the pipe (precisely, the system does it, because the parent terminates). 在您的程序中,父级发送数据,并在5秒钟后关闭管道(确切地说,由于父级终止,系统会执行此操作)。

Keep in mind that a pipe is a device, not a file. 请记住,管道是设备,而不是文件。 This means there is a state when a read can wait for new data. 这意味着当读取可以等待新数据时处于一种状态。 In this state you see the difference between those two read functions: 在这种状态下,您会看到这两个读取函数之间的区别:

  1. When os.read finds no data in the pipe, it waits until the data arrives or the pipe is closed (EOF). os.read在管道中找不到任何数据时,它将等待直到数据到达或管道已关闭(EOF)。 When there is some data in the pipe it returns it immediately. 当管道中有一些数据时,它将立即将其返回。

Read at most n bytes from file descriptor fd. 从文件描述符fd读取最多n个字节。 Return a bytestring containing the bytes read. 返回包含读取的字节的字节串。 If the end of the file referred to by fd has been reached, an empty bytes object is returned. 如果已到达fd引用的文件末尾,则返回一个空字节对象。

  1. When f.read is called without a size limit, it waits till EOF: f.read被调用而没有大小限制时,它将等待直到EOF:

Read and return at most size characters from the stream as a single str. 作为单个str从流中读取并返回最大大小的字符。 If size is negative or None, reads until EOF. 如果size为负或无,则读取直到EOF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM