1

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?

3
  • When system have returned, you check what it returned. If it returns -1 then there was an error. Otherwise the programs main process has run its full course. Commented Aug 22, 2013 at 8:02
  • System() returns -1 if excecution fails. Read docs Commented Aug 22, 2013 at 8:02
  • possible duplicate of return value of system() in C Commented Aug 22, 2013 at 8:03

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.