The program I want to use in my code is a command line tool.
Users type ./program first, and then users can use some command provided by the program.
I want to execute two commands in my source code (myCode.cpp):
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
printf ("Checking if processor is available...");
if (system(NULL)) puts ("Ok");
else exit (EXIT_FAILURE);
printf ("Executing command ...\n");
system ("./program");
system ("command1");
system ("command2");
return 0;
}
After execute my program(./myCode), the program is launched but the two command is not executed.
How to execute the two commands?
How to terminate the program and then execute the following lines of my code? (after system())
To achieve what you want to do, you need to use popen(), not system().
Popen starts a new process that executes the program you specify in the command, and then maps the input or output stream of that program to a file descriptor available in your own program.
Then, you can communicate with this program through this file descriptor.
You code should look like (not actually compiled):
FILE* file = popen("/path/to/your/program", "w")
if (!file) {
// Something not nice happened
}
fprintf(file, "command1\n");
//...
pclose(file);
Use popen() instead of system(), and, assuming your program takes its commands from its standard input, write your commands in the FILE* returned by popen():
FILE* pin = popen("./program", "w");
fprintf(pin, "command1\n");
fprintf(pin, "command2\n");
fflush(pin);
pclose(pin); // this will wait until ./program terminates
Related
I am using MS visual studio 2008, for C coding.
I know we can use
"int system(const char *command)" to execute commands.
Is there any other method to execute system commands in C program.
Also I need to store output of executed command in a variable.
system() function execute command and send output to stdout , is there any way to read from stdout and store in variable.
So my ultimate goal is to execute system command in C program for windows (using visual studio) and store output of that command in a variable.
Any suggestions ?
Standard C libraries give you only one way to execute external command in OS, so use int system(const char *command).
You can save output of this command to text file, and then read this file from you program.
For example:
#include <stdio.h>
#include <stdlib.h>
#define TMP_FILE_NAME "TMP_FOLDER_CONTENT.txt"
int main(int argc, char *argv[])
{
system("dir C:\* > "TMP_FILE_NAME);
FILE * fdir = fopen(TMP_FILE_NAME, "r");
char buff[100];
if (fdir)
{
while (1) {
if (fgets(buff, 100, fdir) == NULL) break;
printf("%s", buff);
}
}
fclose(fdir);
remove(TMP_FILE_NAME);
return 0;
}
Where dir is a program to be executed, C:\* - argument of the program, and > - redirection of standard output for that command after which filename TMP_FOLDER_CONTENT.txt will be substituted.
Also you can check returned value, as:
int errorcode = system("dir C:\* > "TMP_FILE_NAME);
printf("Command executed and returned a value %d\n", errorcode);
or taking into account command you use, change the logic of your program, e.g.:
int errorcode = system("dir C:\* > "TMP_FILE_NAME);
if( errorcode )
{
return errorcode;
}
UPDATE:
Alternatively, you could use pipes in C++, for example as shown in the answer to question How to execute a command and get output of command within C++ using POSIX?
you can do as #VolAnd said or also if you don't care about/don't want the output of the command to be in stdout and you also don't want anything else to be printed to stdout you can use freopen to set stdout to a file of your choice.
I have a binary called TEST which spawns a bash shell, I was hoping to write a C program that runs TEST and then passes commands to the bash shell that it spawns - I have tried the following - can someone indicate if this is possible. I can run the file using, but don't know how to then pass commands to shell it spawns:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
system("/var/testfolder/TEST"); #run the test file
return 0;
}
The UNIX styled popen() function is what you want to use.
See the man page for specifics.
It runs your command in a subprocess and gives you a pipe to interact with it. It returns a FILE handle like fopen() does, but you close it with pclose() rather than fclose(). Otherwise you can interact with the pipe the same way as for a file stream. Very easy to use and useful.
Here's a link to a use case example
Also check out this example illustrating a way to do what you are trying to do:
#include <stdio.h>
int main(void) {
FILE *in;
extern FILE *popen();
char buf[512];
if (!(in = popen("ls -sail", "r")))
exit(1);
while (fgets(buf, sizeof(buf), in) != NULL)
printf("%s", buf);
pclose(in);
}
I want to execute some executable files from inside a C program using system(). I want to ensure that the command executed completely; after that, I want to use the output of the previously executed command. For example:
{
...
...
sprintf(cmd, "./a1.out > temp.txt");
system(cmd);
fp = fopen("temp.txt", "r");
...
...
}
In this example, it is not ensured that cmd executed completely after that the file is opened for reading. And, I want to ensure that. Any help?
You can use popen() to execute the command and read its output directly.
fp = popen("./a1.out", "r");
if (fp) {
...
r = pclose(fp);
if (r < 0) {
/*...command exited abnormally */
}
} else {
/*...fork or pipe error */
}
You can choose to write the data to a file if that is what is required.
I don't know about the os you are using but under Linux the manual says
system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed.
Moreover Posix says
The system() function shall not return until the child process has terminated.
So you are sure that the command is completed.
I am basically trying to check if a particular file exists or not. For that I am using the test command of Unix.
sprintf(execbuf, "%s if test -r %s ; then true; else exit; fi;",
execbuf, st->file, NO_FILE);
It works fine, but I do not want to exit if the file is not here, rather it should return FAIL.
I am not able to figure out how to make the program return FAIL. I was thinking of using the exit code from the above command, but still I am not able to figure out how to use that exit code outside the Linux command in the program.
I'd recommend you rather just use the access() call, and not execute external shell commands to figure this out.
Just be aware that such cases are subject to race conditions - the file might exist when you call access() (or execute a shell command that determines whether the file exists), but it might be gone when you actually need it later on. If that's a problem for you, just open() the file, and use the file descriptor later on when you actually need it for I/O.
If you're not married to what your doing right now, then I'd suggest using stat:
#include <sys/stat.h>
#include <stdio.h>
int main (int argc, char** argv[])
{
struct stat sts;
if (stat(argv[1], &sts) == -1 && errno == ENOENT)
printf ("The file %s doesn't exist...\n", argv [1]);
else
printf("The file exists\n");
This will tell you if it exists or not. If you dont' want to pass it command line, parameter 1 is a const char*, so just pass it the file name.
I am trying to run a script inside my C program using system() command. Inside main(), I run the script and it returns the results. How can I put the result of the script in some string and check for conditions? I know I can do it with files but was wondering if its possible to put the result into a string.
Sample would be like:
main()
{
system("my_script_sh"); // How can I get the result of the my_script_sh
}
You can't use the system command for that. The best thing to do is use popen:
FILE *stream;
char buffer[150];
stream = popen("ls", "r");
while ( fgets(buffer, 150, stream) != NULL ){
// Copy the buffer to your output string etc.
}
pclose(stream);
Use popen() and read the stream into a char * buffer.
Well the easiest thing to do would be to take system("my_script_sh") out of your program and invoke the program from the shell with a pipe -- e.g.: my_script_sh | ./your_c_program and then your C program just reads from stdin (file descriptor 0).
If that is not possible, then have a look at man 3 popen. Basically, you use popen instead of system and it gives you a file handle that you can read from to get the output of the program.
Here are a few links that might be useful:
http://pubs.opengroup.org/onlinepubs/009695399/functions/popen.html
http://www.crasseux.com/books/ctutorial/Programming-with-pipes.html
http://www.metalshell.com/source_code/23/Popen.html
http://tldp.org/LDP/lpg/node12.html