2

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())

Adam Liss
  • 47,594
  • 12
  • 108
  • 150
user2261693
  • 405
  • 3
  • 7
  • 11
  • did you check what errors system() repots? – Balog Pal Jun 14 '13 at 13:54
  • 1
    The `system` command executes its argument in a shell, so each of your calls is independent of the others; they don't pass the two commands to the program. See http://linux.die.net/man/3/popen to learn how to open a pipe between your C program and `./program`. – Adam Liss Jun 14 '13 at 13:56
  • To learn how to launch a new process with bidirectional communication, see http://stackoverflow.com/questions/5094063/fork-pipe-and-exec-process-creation-and-communication – Adam Liss Jun 14 '13 at 14:12

2 Answers2

2

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);
Matthieu Rouget
  • 3,289
  • 18
  • 23
1

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
Adam Liss
  • 47,594
  • 12
  • 108
  • 150
rectummelancolique
  • 2,247
  • 17
  • 13
  • The program will not terminate unless users use "ctrl+c"... pclose(pin) just wait rather than terminates the program, right? – user2261693 Jun 14 '13 at 14:22
  • pclose just waits indeed. ./program has to be closed by something else for pclose to return. I suggest you implement a "quit" command in ./program and then fwrite(pin, "quit\n"). Just killing the parent process may be a bit dirty. – rectummelancolique Jun 14 '13 at 14:32