Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C-Interface for interactive bash

Tags:

c

linux

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.

like image 624
highsciguy Avatar asked Nov 14 '22 02:11

highsciguy


1 Answers

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.

like image 128
FooF Avatar answered Jan 28 '23 11:01

FooF