|
#! /Usr/bin/env python
Import select
# Import the select module
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 ):
# Check whether all file descriptors are valid
Return 0
While True:
# Start to use select to monitor all input file descriptors
Rs, ws, es = select. select ([fromfd1, fromfd2], [], [])
For r in rs:
If r is fromfd1:
# Read data when the first file descriptor is readable
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 ()
|