Tim Watts
Tim Watts

Reputation: 23

Interacting with a Shell using C

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;
}

Upvotes: 2

Views: 2300

Answers (1)

clearlight
clearlight

Reputation: 12615

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);
}

Upvotes: 3

Related Questions