Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Returning the actual value from a simple unix cmd

Status
Not open for further replies.

cptk

Technical User
Mar 18, 2003
305
0
0
US
Is there a simpler way/method to get the return value from a unix cmd then to use the following method:

FILE *in;
char cmd[5] = "pwd";
char buf[100];

in = popen(cmd, "r");
fgets(buf,100,in);
/* or use some form of fscanf(in,%s,buf); */
pclose(in);

It seems that "popen" is the only way to get the actual return value(s). I use this method when I need to process a lot of data, but when I know it's just a one line return value from a unix cmd (e.g. - pwd, date, some grep cmd etc.), it's just seems overkill to have to use popen and the FILE pointers.


 
popen is the best way. Some of the others you've mentioned eg date, have C equivalents so you don't need to use the Unix commands.
 
getcwd is the API equivalent of the pwd command.



--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Yes, I know a few of my examples wouldn't actual require the popen method (e.g. date, pwd).

I was just trying to quickly illustrate some unix cmds that return singular results.

So I'm gathering it's true that there's no other means then to use a popen?
 
Well the other possible ways are even more long winded.

1. There's always roll your own using fork/exec/wait to organise the processes, open/close/dup to organise the file descriptors and read/write to get the information.

2. Or a poor substitute is to use system() to run the command to redirect to a file, then use regular fopen() to read the temp file. But then there's the removing the file when you're done.

> but when I know it's just a one line return value from a unix cmd (e.g. - pwd, date, some grep cmd etc.),
> it's just seems overkill to have to use popen and the FILE pointers.
So write your own function which runs a command and returns a single line, if that is the kind of thing you need to do a lot.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Salem -

If you mean write a general function that takes as an argument the char cmd to run in popen, that's what I already did.

Thanks ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top