| #!/usr/bin/env python import select #匯入select模組 BLKSIZE=8192 def readwrite(fromfd,tofd): readbuf = fromfd.read(BLKSIZE) if readbuf: tofd.write(readbuf) tofd.flush() return len(readbuf) def copy2file(fromfd1,tofd1,fromfd2,tofd2): ''' using select to choice fds''' totalbytes=0 if not (fromfd1 or fromfd2 or tofd1 or tofd2) : #檢查所有檔案描述符是否合法 return 0 while True: #開始利用select對輸入所有輸入的檔案描述符進行監視 rs,ws,es = select.select([fromfd1,fromfd2],[],[]) for r in rs: if r is fromfd1: #當第一個檔案描述符可讀時,讀入資料 bytesread = readwrite(fromfd1,tofd1) totalbytes += bytesread if r is fromfd2: bytesread = readwrite(fromfd2,tofd2) totalbytes += bytesread if (bytesread <= 0): break return totalbytes def main(): fromfd1 = open("/etc/fstab","r") fromfd2 = open("/etc/passwd","r") tofd1 = open("/root/fstab","w+") tofd2 = open("/root/passwd","w+") totalbytes = copy2file(fromfd1,tofd1,fromfd2,tofd2) print "Number of bytes copied %d\n" % totalbytes return 0 if __name__=="__main__": main() |