我想在我的代码中像 shell 本身一样执行 cd 命令... 我的代码将询问用户整个命令,如“cd/desktop”,我尝试使用 chdir(path),但在我的代码中执行 cd 的部分存在错误..请帮助
void main(void) {
char in[512];
pid_t id;
int status,x,y,i = 1;
char *f[512];
char *v;
char *s;
while(1)
{
printf("shell>");
fgets(in,512, stdin);
int size = strlen(in);// calculate dim of in execpt null
in[size-1] = '\0'; //null at the end because ls\n not executable
v = strtok(in, " ");
f[0] = v;
while (v = strtok(NULL, " ")){
f[i] = v;
i++;
}
f[i] = NULL;
y=strcmp(f[0],"exit");
if(y==0)
break;
x=strcmp(f[0],"cd");
if(x==0){
s=f[2]; // this should be the path is it right?
chdir(s);
}
id=fork();
if (id==0){ //child
execvp(f[0],f);
perror("failure");
exit(1);
}
else //parent
{
waitpid(id,&status,0);
}
}
}
最佳答案
我认为你至少应该搬家
i = 1;
进入while循环,即
while(1)
{
i = 1;
进一步
s=f[2]; // this should be the path is it right?
我希望它是f[1]
基于您的代码的示例
#include <string.h>
#include <stdio.h>
int main(void) {
char in[512];
int status,x,y,i = 1;
char *f[512];
char *v;
char *s;
char cwd[1024]; // ADDED THIS
while(1)
{
i = 1; // ADDED THIS
getcwd(cwd, sizeof(cwd)); // ADDED THIS - print current dir
fprintf(stdout, "%s - ", cwd);
printf("shell>");
fgets(in,512, stdin);
printf(" %s", in); // ADDED THIS
int size = strlen(in);// calculate dim of in execpt null
in[size-1] = '\0'; //null at the end because ls\n not executable
v = strtok(in, " ");
f[0] = v;
while (v = strtok(NULL, " ")){
f[i] = v;
i++;
}
f[i] = NULL;
y=strcmp(f[0],"exit");
if(y==0)
break;
x=strcmp(f[0],"cd");
if(x==0){
s=f[1]; // CHANGED THIS
printf("path=%s\n", s); // just a print for debug
//chdir(s); // just removed for debug
}
}
return 0;
}
输入:
cd dir1
cd dir2
exit
输出:
shell> cd dir1
path=dir1
shell> cd dir2
path=dir2
shell> exit
关于c - 用于执行shell指令的shell代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36085139/