C program code to run a Linux command line
I would like a C program code to run a Linux command line such as ifconfig, testparm and others.
Below is a simple C program code, what command would I use so that this little program will execute the command ifconfig. If there is any syntax error below, please fix it also. ======================================== #include <stdio.h> int main() { char *linux-command [] linux-command = "ifconfig" # What function would I call so that linux-command would be # execute as if the user in on a command line console. } |
Please do not post the same thread in more than one forum. Picking the most relevant forum and posting it once there makes it easier for other members to help you and keeps the discussion all in one place.
http://www.linuxquestions.org/rules.php |
system, defined in stdlib.h. check out man 3 system for definition
|
please post on the forum and dont email me personally, thank you
i am not a linux programmer so this probably isnt perfect. do you know what pipes are? if not read about them. there is a function in stdio, popen that returns a FILE pointer but for a pipe instead of a file. read about popen then try the following FILE *f; f = popen("ls", "r"); // here you can use f as you would any normal FILE pointer but it // contains the output of the ls command pclose(f); obviously you want to add some error checking in there and replace ls with ifconfig or whatever command you want to execute. |
// You can use system() function
#include <stdio.h> int main() { system("clear"); system("ifconfig"); } |
I'm assuming that this would also apply to C++?
(I've been searching for info on this, but didn't know what to ask myself). |
Yes, you can use stdio.h in C++ as well. Basically with a few rare incompatibilites, you can use anything in C in C++.
|
Quote:
|
Well, my assumption is the output is displayed to the screen, like is the case with system("ls");
Now the more interesting question is, is there anyway to *capture* the output and use it directly in your program? Obviously you could send the ouput of the command to a file and then read from the file. No, i am talking about whether or not you can do it without creating any files. *Goes of hunting for answers* |
this is about the third time i have posted the same thing on this forum but nevermind. the output of a command can be captured by using popen() in stdio.h. its quite simple if you read the man pages.
|
Excellent, thanks.
For some reason, most of my "programming buddies" didn't know how to do it. |
All times are GMT -5. The time now is 06:56 PM. |