[This question is for UNIX/Linux users.] Create an output filter that performs word wrap- ping. If a line is longer than a certain number of characters, split the line over multiple lines. The num- ber of characters per line should be indicated in the command line. The program should read in keyboard input from the user, and format that input as specified, placing the result in file.txt.

Implement this using pipes and fork functions (child gets input from user, parent performs the fil- tering).

What will be an ideal response?

```
#!/usr/local/bin/python

import os
import sys

# open parent and child read/write pipes
parentReadPipe, childWritePipe = os.pipe()

pid = os.fork() # fork child

if pid == 0: # child

# close unneeded pipe
os.close( parentReadPipe )

userInput = raw_input( "Please enter lines of text: " )
while userInput != "":
os.write( childWritePipe, userInput )
userInput = raw_input()

# close pipes
os.close( childWritePipe )

# exit
sys.exit( 0 )

elif pid != 0: # parent

# close unneeded pipe
os.close( childWritePipe )

# open file
try:
file = open( "file.txt", "w" ) # open file in write mode
except IOError, message: # file open failed
print >> sys.stderr, "File could not be opened:", message
sys.exit( 1 )

if len( sys.argv ) == 1:
print "No wrap size specified, reverting to 42"
wrap = 42
else:
wrap = int( sys.argv[ 1 ] )

# read value from child Read pipe
currentLine = os.read( parentReadPipe, wrap )

while currentLine:
print >> file, currentLine
currentLine = os.read( parentReadPipe, wrap )

# close pipes
os.close( parentReadPipe )
file.close()
else:
sys.exit( "Could not fork" )
```
Please enter lines of text: One two three four five
six seven eight nine ten
eleven twelve thirteen
---Contents of file.txt---
One two th
ree four f
ive
six seven
eight nine
ten
eleven twe
lve thirte
en

Computer Science & Information Technology

You might also like to view...

When working with a chart, you click the ________ to display the CHART TOOLS

Fill in the blank(s) with the appropriate word(s).

Computer Science & Information Technology

The _____ method is similar to theapply()method except that the argument values are placed in a comma-separated list of values instead of an array.

A. shuffle() B. sort() C. call() D. create()

Computer Science & Information Technology