Advertisement

UNIX - Response from command line

Started by July 19, 2003 06:51 AM
7 comments, last by Cortez 21 years, 1 month ago
How can get the response of OS into a string (like, after system("pwd"); )? (I know i can get the current dir without using pwd, it''s rather a general question on command line response).
Setup a pipe and fork the process. In the child process close STDOUT (capitalized purposely) and duplicate (dup) the input end of the pipe (it''s kind of strange, but this causes the input end of the pipe to get STDOUT''s role). In the parent process, wait for the child to end ("waitpid") and read whatever you want out of the output end of the pipe.

Advertisement
A simpler approach is to use popen(). You would do something like:

FILE *fp = popen("mycommand my parameters","r");while (fgets(str,size,fp)){do something with str}fclose(fp); 


Basically, popen() forks a process for the specified command and attaches that process'' input (if mode is "w") or output (if the mode is "r") to the FILE stream.
If you happen to be using Perl, then
$string = `pwd`; 

will do the trick. It works in shell scripts, too.
Thanks

Put when reading with pipe, I noticed a "while". So there''s more than 1? In an example, say these''re on the screen:

>Line1
>Line2
>Line3
>NextisCurrentInputLine_ThisIsLine4
>_

Now, if we call fread for the pipe, 1st it''ll read 4th, then 3rd, and so on, or it works differently?
It works just like reading from a file. The first line read would be "Line 1".
Advertisement
Moving by request of the original poster.

-fel
~ The opinions stated by this individual are the opinions of this individual and not the opinions of her company, any organization she might be part of, her parrot, or anyone else. ~
not sure if this is related, but is it possible to map a file
descriptor or handle to a memory block? sort of like the opposite
of mmap in unix?
I''m not sure what you mean by "the opposite of mmap." mmap maps a file to a block of memory. Are you talking about mapping to a pre-allocated block? If so, I don''t know of a function to do that.

This topic is closed to new replies.

Advertisement