|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Calling a shell command in C code
The code below worked. It showed all of the parameters of the shell command ifconfig. Now, I would like to stored its output in a variable as in
string_result = system(string1); The above code does not work. 1) What command that I need to run to stored the result of a shell command in a variable in C program ? ====================================== #include <stdio.h> #include <stdlib.h> int system(const char *string1); int main() { char string1[] = "ifconfig"; system(string1); return(0); } |
|
#2
|
||||
|
||||
|
pipe the output of the command to a file and then read in the file.
|
|
#3
|
|||
|
|||
|
Hi, i have the same problem you posted. Would you please let me know when you find the solution?
I found this command: _system_r(), and it is supposed to work but when linking with gcc linker it returns "udefined reference to '_system_r'". Do you know why? Please, stay in touch. Thanx Luis Molina ![]() |
|
#4
|
||||
|
||||
|
I tried answering earlier, but we had terrible access problems at work. As a result, the sample code I had written is lost. So now I'm at home and late for bed, so I'll be terse.
The piping should be done with the popen function call. You pass it a string with the command and the open option (just like fopen). Also like fopen, it returns a FILE* which you then use to fread or fgets just as you would from a text file on disk. The only difference would be that you use pclose to close the pipe when you are done. For example: FILE* fp = popen("ifconfig","r"); // open a shell and run ifconfig, then read its output. The command string can also contain options and parameters. That should get you started. |
|
#5
|
|||
|
|||
|
Solution
/* Hola, esta es una solucion que yo encontre a ese problema que tambien tube. */
#include<stdio.h> #include<string.h> main() { // FILE *popen(const char *orden, const char *tipo); FILE *f; int i; char cadena; char cad[300]; f = popen("ping -w 1 127.0.0.1 ","r"); //>> /root/TesisNetsaint/Pesca/result.txt for ( i=0 ; i <=280 ; i++) // 280 = Size of the result { //printf( "%c", fgetc(f) ); cad[i] = fgetc(f) ; } // Bueno!!!! cad[i]= '\o' ; printf("%s",cad); if( strstr(cad,"0 packets received") ){ printf("Host DOWN"); }else{ printf("Host UP"); } } |
|
#6
|
||||
|
||||
|
Re: Solution
Quote:
¿No debe ser cero? Como '\0'. Shouldn't that be a zero, as in '\0'? |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Calling a shell command in C code |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|