|
#!/usr/bin/env python
import select
BLKSIZE=8192
def readwrite(fromfd,tofd):
readbuf = fromfd.read(BLKSIZE)
if readbuf:
tofd.write(readbuf)
tofd.flush()
return len(readbuf)
def copyPoll(fromfd1,tofd1,fromfd2,tofd2):
#定義需要監聽的事件
READ_ONLY = (select.POLLIN |
select.POLLPRI |
select.POLLHUP |
select.POLLERR )
totalbytes=0
if not (fromfd1 or fromfd2 or tofd1 or tofd2) :
return 0
fd_dict = {fromfd1.fileno():fromfd1,fromfd2.fileno():fromfd2}
#建立poll對象p
p=select.poll()
#利用poll對象p對需要監視的檔案描述符進行註冊
p.register(fromfd1,READ_ONLY)
p.register(fromfd2,READ_ONLY)
while True:
#輪詢已經註冊的檔案描述符是否已經準備好
result = p.poll()
if len(result) != 0:
for fd,events in result:
if fd_dict[fd] is fromfd1:
if events & (select.POLLIN|select.POLLPRI):
bytesread = readwrite(fromfd1,tofd1)
totalbytes+=bytesread
elif events & (select.POLLERR):
p.unregister(fd_dict[fd])
if fd_dict[fd] is fromfd2:
if events & (select.POLLIN|select.POLLPRI):
bytesread = readwrite(fromfd2,tofd2)
totalbytes+=bytesread
elif events & (select.POLLERR):
p.unregister(fd_dict[fd])
if bytesread <= 0:
break
return totalbytes
def main():
fromfd1 = open("/etc/fstab","r")
fromfd2 = open("/root/VMwareTools-8.8.1-528969.tar.gz","r")
tofd1 = open("/root/fstab","w+")
tofd2 = open("/var/passwd","w+")
totalbytes = copyPoll(fromfd1,tofd1,fromfd2,tofd2)
print "Number of bytes copied %d\n" % totalbytes
return 0
if __name__=="__main__":
main()
|