reliable reads from pipes
Guy Harris
guy at auspex.auspex.com
Sun Aug 5 10:31:37 AEST 1990
>The following program does not work all the time. Most of the times it works
>(gives the correct directory (/users/prog/test) followed by a carriage return)
>but sometimes it does not print out the full directory name (prints (/) not
>followed by a carriage return.) I am not sure whether it is not reading from
>the pipe completely or not printing out the complete message. Any ideas and/or
>suggestions for improvements? I am trying to write a program which calls
>another program passing it some parameters and getting back some output.
Given that, I assume the reason you're running "pwd" is to test the
logic you're using to run the subprocess, not because you actually want
to write your own code to get the current working directory. If you
want to get the current working directory, check first whether your OS
supplies such a routine; it's likely to be called either "getwd()" or
"getcwd()". "getcwd()" is the offical POSIX version, and as such will
eventually be more likely to be available than "getwd()".
(BTW, if you want to run "pwd", be warned that a bad setting of PATH
will, in your example, either not find "pwd" at all or find the wrong
one. You might want to just have it "exec" "/bin/pwd" and, if that
fails, "/usr/bin/pwd" instead.)
If you want to run some program and read its standard output, check out
"popen()", which your UNIX system almost certainly has. It does most of
the work your code is doing, and you thus don't have to write that code
yourself, or make it work. "'libc' is your friend."
In addition, note that there is *no* guarantee that a single "read()"
will necessarily pick up all the data that the program will write to the
pipe; you need to keep reading until you get an EOF, or until you know
you've read all you need to read. "popen()" gives you a standard I/O
stream, which can make it a bit more convenient to keep reading.
More information about the Comp.unix.questions
mailing list