2

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;
}
lurker
  • 56,987
  • 9
  • 69
  • 103
  • What exactly do you want to happen? Do you simply want to send commands to the shell, and let the shell write to standard output and standard error, or do you want to be able to have your controlling program write commands to the shell and read the shell's responses (and if the latter, do you need to handle standard output and standard error jointly or separately)? You may find [Can `popen()` make bi-directional pipes like `pipe()` and `fork()`?](http://stackoverflow.com/questions/3884103/can-popen-make-bidirectional-pipes-like-pipe-fork/) helpful. – Jonathan Leffler Mar 22 '15 at 20:54

1 Answers1

3

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);
}
clearlight
  • 12,255
  • 11
  • 57
  • 75