假设我们有一个 shell 在终端上运行,比方说,/dev/pts/1。 shell 已经在运行,我们无法重新启动它。
现在我们要编写一个 C 程序来“控制”shell,即它本身会为用户提供一个类似 shell 的界面,读取用户的输入,将其传递到/dev/pts/上的真实 shell 1,让它执行它,读取 shell 的输出并将其打印回给用户。
我知道如何完成这项任务的一半:我知道如何收集用户的输入并将此输入注入(inject)“真实 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 的输出。
有什么建议吗?
最佳答案
您可以使用 pipes为了那个原因。 Linux shell 允许重定向。
我使用管道来控制 tty。
关于c - Linux:写一个C程序,那个 'controls'一个shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4747306/