Linux:编写一个“控制”C 程序一个贝壳
假设我们有一个在终端上运行的 shell,比如说 /dev/pts/1。 shell 已经在运行,我们无法重新启动它。
现在我们要编写一个C程序来“控制”shell,即它本身向用户提供一个类似shell的界面,读取用户的输入,将其传递到/dev/pts/1上的真实shell,有它执行它,读取 shell 的输出并将其打印回用户。
我知道如何完成此任务的一半:我知道如何收集用户的输入并将此输入注入到“真实 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++ ) ioctl(tty, TIOCSTI, buf);
}
close(tty);
}
else printf("Failed to open terminal %s\n", argv[1]);
}
return 0;
}
上面的内容会将您的输入传递到在终端中运行的 shell(在第一个参数中给出其名称)并且让 shell 执行它。但是,我现在不知道如何读取 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++ ) ioctl(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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 管道 来实现这一点。 Linux shell 允许重定向。
我用管道来控制tty。
You can use pipes for that. Linux shells allow redirection.
I used pipes to control tty's.
有些程序允许您更改进程的控制终端:reptyr和 injcode 就是两个这样的程序。
然而,我确实相信他们会切断另一个终端,所以根据您的需要,这可能完全适合也可能不完全适合。
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.
请查看 libpipeline。也许这会帮助你......
please take a look at libpipeline. maybe this will help you...