Example 2: Executing UNIX commands
Read the output of a command
This program executes the ls command, read from the standard output stream of the command, to display the file names and extensions separately.
The second parameter of the openPipe()
method is "r"
, only to read from the standard
output of the command:
MAIN
DEFINE fn, ex STRING
DEFINE ch base.Channel
LET ch = base.Channel.create()
CALL ch.setDelimiter(".")
CALL ch.openPipe("ls -1","r") -- Warning: ls option is -1 (digit one)
WHILE ch.read([fn,ex])
DISPLAY "Filename: ",fn, COLUMN 40,
"ext: ",NVL(ex,"NONE")
END WHILE
CALL ch.close()
END MAIN
Write and read from a command
The next program executes the tr command, writing to its standard input stream and reading the standard output stream.
The second parameter of the openPipe()
command is "u"
, to read and write from/to the
command. Note that we must force the tr command to flush each line written to
stdout, with the stdbuf -oL command:
MAIN
DEFINE ch base.Channel, x INTEGER
LET ch = base.Channel.create()
--CALL ch.openPipe("tee file.tmp","u") -- OK
--CALL ch.openPipe("tr '[:lower:]' '[:upper:]'","u") -- Hangs in readLine()
CALL ch.openPipe("stdbuf -oL tr '[:lower:]' '[:upper:]'","u") -- OK
FOR x=1 TO 3
CALL ch.writeLine(SFMT("line #%1",x))
DISPLAY ch.readLine()
END FOR
CALL ch.close()
END MAIN