Linux: write a C program that 'controls' a shell
Suppose we have a shell running on terminal, let's say, /dev/pts/1. The shell is already running and we can't restart it.
Now we want to write a C program that will 'control' the shell, i.e. which will itself provide a shell-like interface to the user, read user's input, pass it on to the real shell on /dev/pts/1, have it execute it, read shell's output and print it back to the user.
I know how to do half of this task: I know how to gather user's input and inject this input to the 'real shell' :
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#define SIZE 100
int main(int argc, char** argv)
{
if( argc>1 )
{
int tty = open( argv[1], O_WRONLY|O_NONBLOCK);
if( tty!=-1 )
{
char *buf,buffer[SIZE+1];
while(1)
{
printf("> ");
fgets( buffer, SIZE, stdin );
if( buffer[0]=='q' && buffer[1]=='u' && buffer[2]=='i' && buffer[3]=='t' ) break;
for(buf=buffer; *buf!='\0'; buf++ ) ioc开发者_开发知识库tl(tty, TIOCSTI, buf);
}
close(tty);
}
else printf("Failed to open terminal %s\n", argv[1]);
}
return 0;
}
The above will pass on your input to shell running in terminal ( give its name in the first argument ) and have the shell execute it. However, I don't know how to read the shell's output now.
Any tips?
You can use pipes for that. Linux shells allow redirection.
I used pipes to control tty's.
There are programs that allow you to change the controlling terminal for a process: reptyr and injcode are two such programs.
I do believe that they sever the other terminal, however, so depending on your needs this may or may not fit exactly.
please take a look at libpipeline. maybe this will help you...
精彩评论