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?

  • 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. – Some programmer dude Aug 22 '13 at 08:02
  • System() returns -1 if excecution fails. Read [docs](http://linux.die.net/man/3/system) – Zigma Aug 22 '13 at 08:02
  • possible duplicate of [return value of system() in C](http://stackoverflow.com/questions/8654089/return-value-of-system-in-c) – Zigma Aug 22 '13 at 08:03

2 Answers2

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.

jxh
  • 69,070
  • 8
  • 110
  • 193
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.

hivert
  • 10,579
  • 3
  • 31
  • 56