calling commands using 'system()' from inside a program - c

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.

Related

How to handle a c++ file compile inside a C server?

I need to make a server that:
1) compiles a c++ file and saves the errors in a file if they exist;
2) if there are no errors i must run the a.out file and extract the output in another file.
The problem resides in the first one.
In order to compile and extract errors i used more methods:
1) system("g++ file.cpp &> err.txt") - not working: it prints the errors in the console but the file remains empty
2) popen - Reference link: C: Run a System Command and Get Output? : the only difference is that i opened another file and instead of printing in the console i used fprintf to write in file.
I forgot to add that the first method works if written as command in console but inside the server is problematic.
// This code is to show what i have already tried and if you find any
// syntax errors like ; or ' pls ignore them as i couldn't copy the code
// from the docker console. Thank you very much!
//1
system("g++ file.cpp &> err.txt");
if( access( "a.out", F_OK ) != -1 ) {
system("./a.out > output.txt");
//2
FILE *f;
char buff[200];
f = popen("g++ file.cpp", "r");
if (f == NULL) {
printf("Failed to run command\n" );
exit(1);
}
FILE *o;
o = fopen("err.txt", "w");
while (fgets(buff, sizeof(buff)-1, f) != NULL) {
fprintf(o, "%s", buff);
}
fclose(o);
fclose(f);
I expected the errors to be written in the err.txt not to be printed in console and in all the above examples it prints in the console and err.txt remains empty.
You can accomplish it the old-school way:
fork() and in the child:
Open a file for storing standard output and another one for errors.
Use dup2(oldfd, newfd) to duplicate the two files' descriptors to stdout, and stderr respectively.
Invoke execlp with gcc and its arguments.
In the parent process you can add waitpid call to wait for the child to finish.
Ok so in the end apparently this one was pretty close: system("g++ file.cpp &> err.txt");
The solution is: system("g++ file.cpp > err.txt 2>&1");

popen() is successfull for all commands

No matter what "cmd" string is passed in popen(), it is never FAILING for me
So fp is never NULL even for random "cmd" string.
FILE *fp;
char path[1035];
char cmd = "randomrandomrandom";
fp = popen(cmd, "r");
if (fp == NULL) {
//Handle Error
exit(1);
}
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
}
pclose(fp);
popen runs an instance of the shell. Starting a shell normally succeeds. You need to determine if it has terminated successfully. popen itself cannot do that, but pclose can: it returns the status of the child process (or -1 if another error has occurred).
So in order to verify that the command has been executed successfully, one needs to check return values of both popen and pclose.
It seems to be behaving as expected:
http://pubs.opengroup.org/onlinepubs/009695399/functions/popen.html
As you can see, popen only fails when its internal pipe command fails--the stream cannot be opened. For example, all the file descriptors are in use

How many ways are there to execute system command in C program for windows

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.

Execute a program in my C code

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

How to execute a bash command in C and retrieve output?

I'm trying to execute a bash command from c and retrieve and show the result.
I've tried with system but it doesn't work.
My code looks like:
char command[200];
sprintf(command,"lsof -iTCP:%d | cut -d\"\" -f1 | tail -1",port);
printf("Port %d is open\n and is listened by %s",port,system(command));
Please help. I need this .
Edit aside from the actual question, I'd be using
sudo netstat -tlpn
(shows the processes that are listening on TCP ports, not resolving the ports/addresses)
Perhaps combine it with a bit of grep:
sudo netstat -tlpn | grep :7761
to find where port :7761 is being listened?
You can use popen.
With popen you get the benefit that you receive the process output asynchronously (you will be able to stop processing if the answer is on the first line of output without having to wait for the subprocess to complete; simply pclose and the subprocess will die with SIGPIPE)
A sample straight from the Standards Documentation:
The following example demonstrates the use of popen() and pclose() to execute the command ls * in order to obtain a list of files in the current directory:
#include <stdio.h>
...
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
while (fgets(path, PATH_MAX, fp) != NULL)
printf("%s", path);
status = pclose(fp);
if (status == -1) {
/* Error reported by pclose() */
...
} else {
/* Use macros described under wait() to inspect `status' in order
to determine success/failure of command executed by popen() */
...
}
system(command) returns the return code of the command, not its output.
If you want to read the output of a command, you should use popen
This returns a file descriptor to the output, which you can read from just like a normal file.

Resources