[英]Unable to change directory with remote shell
I have been trying my hand at creating a remote shell in C for Unix. 我一直在尝试用C为Unix创建一个远程shell。 I am able to connect to the server and pull commands off of it.
我能够连接到服务器并从中拉命令。 However I am unable to change my pwd, even though seems to operating correctly.
但是,即使看起来运行正确,我也无法更改我的密码。 I give it a directory and if that directory does not exist I will receive an error.
我给它一个目录,如果该目录不存在,我将收到一个错误。 Below is the quick shell I have been testing.
下面是我一直在测试的快速外壳。
while(1)
{
for( n = 0; n < BUFFER_SIZE; n++)
{
command[n] = '\0';
}
write( sockfd, buffer, strlen( buffer ) );
read( sockfd, command, BUFFER_SIZE );
fprintf( stderr, "Command: %s\n", command );
dup2(sockfd, 2);
dup2(sockfd, 1);
dup2(sockfd, 0);
execlp( "/bin/sh", "sh", "-c", command, (char *)NULL );
} }
cd
is not a program, it is a shell builtin command, which changes the cwd for the shell, not for the program that spawned that shell. cd
不是程序,它是shell的内置命令,它将更改shell的cwd,而不是生成该shell的程序的cwd。 You are spawning a new shell for every command, so the changed cwd does not persist. 您正在为每个命令生成一个新的shell,因此更改后的cwd不会持久存在。
You could either try to catch invocations of cd
and run chdir()
yourself, or spawn a single interactive shell and use pipes or a pty (pseudo terminal) to communicate with it. 您可以尝试捕获
cd
调用并自己运行chdir()
,也可以生成单个交互式shell并使用管道或pty(伪终端)与之通信。
exec
'ing a cd
command doesn't change the working directory of the program that calls exec
. exec
的cd
命令不会更改调用exec
的程序的工作目录。 It forks a process that changes its own working directory, then exits. 它派生一个进程来更改其自己的工作目录,然后退出。
You'll have to treat the cd
command specially by invoking the chdir
system call for it rather than exec
. 您必须通过调用
chdir
系统调用而不是exec
来特别对待cd
命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.