highsciguy
highsciguy

Reputation: 2637

C-Interface for interactive bash

I am searching for a C interface for bash shells. I.e. I would like to have a set of functions which allow me to open a session, execute commands, return the output (STDOUT,STDERR) and finally to close the shell. It could be a library or C source code based on standard libraries.

Upvotes: 5

Views: 2826

Answers (2)

FooF
FooF

Reputation: 4462

The general root problem seems to be how to programmatically run interactive terminal program.

Now this would in my part require actual testing, but you would roughly need to

  1. create three pipes corresponding to child process stdin, stdout, and stderr (the parent process writing to stdin_pipe and reading stdout_pipe and stderr_pipe) using pipe(2) system call;
  2. fork and in the child close redirect the standard in, out and error to the proper ends of the above pipes by calling dup2(2);
  3. exec (execve(2) / execv(3)) your interactive shell;
  4. start writing commands to stdin_pipe and reading the errors and responses from the other two pipes.

(If you do not need to make the distinction between stdout and stderr you could just simplify your life by using popen(3) - you could probably redirect stderr to stdout by proper choice of command string).

For properly working solution, however, I believe you probably would need to use pseudo ttys (pty(7)) by calling forkpty(3) instead of just fork.

As it starts to get more and more complicated to take into account all the nyances of dealing with pseudo terminals, why not search for C expect library which should be able to do all this for you. Or emulate how expect or some other language equivalent like pexpect is implemented. Actually expect seems to provide a C library called libexpect(3) for you so that you do not need to write tcl/tk for programming the interaction. I am not personally familiar with the library, and there could be other better ones.

Upvotes: 1

nav_jan
nav_jan

Reputation: 2553

Are you looking to achieve something like this:

    #include<stdio.h>
    int main()
    {
      char a[1000];
      gets(a);
      system(a);
      return 0;
    }

Output:

./a.out
cat testing.c
#include<stdio.h>
int main()
{
  char a[1000];
  gets(a);
  system(a);
  return 0;
}

gets() and system call can get inside a loop.

Upvotes: 0

Related Questions