C 用于执行shell指令的shell代码
我想执行cd命令,就像我代码中的shell一样。。。 我的代码将向用户询问整个命令,如“cd/desktop”,我尝试使用chdir(path),但在我的代码中执行cd的一部分有一个错误。。请帮忙C 用于执行shell指令的shell代码,c,shell,C,Shell,我想执行cd命令,就像我代码中的shell一样。。。 我的代码将向用户询问整个命令,如“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) { pri
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;
}
#包括
#包括
内部主(空){
[512]中的字符;
整数状态,x,y,i=1;
char*f[512];
char*v;
char*s;
char cwd[1024];//添加了这个
而(1)
{
i=1;//添加了这个
getcwd(cwd,sizeof(cwd));//添加了这个-打印当前目录
fprintf(标准输出,“%s-”,cwd);
printf(“shell>”);
fgets(in,512,stdin);
printf(“%s”,in);//添加了这个
int size=strlen(in);//计算in execpt null的尺寸
在[size-1]='\0';//结尾处为null,因为ls\n不可执行
v=strtok(单位为“”);
f[0]=v;
while(v=strtok(NULL,“”){
f[i]=v;
i++;
}
f[i]=NULL;
y=strcmp(f[0],“退出”);
如果(y==0)
打破
x=strcmp(f[0],“cd”);
如果(x==0){
s=f[1];//更改了此
printf(“路径=%s\n”,s);//只是一个用于调试的打印
//chdir(s);//刚刚删除以进行调试
}
}
返回0;
}
输入:
cd-dir1
cd-dir2
出口
输出:
shell>cd-dir1
路径=dir1
shell>cd-dir2
路径=dir2
外壳>出口
@莫森-你能更具体一点吗-当我做你的修改时,什么是不工作的,它没有实现cd!!i、 e更改当前目录首先注释掉
chdir
并放入printf(“路径=%s\n”,s)
检查字符串是否正确。字符串是否正确,但当我运行代码时,没有发现这样的文件或目录。。。。当我键入“cd testdir”时,我在桌面上创建了一个名为“testdir”的文件。输出正确打印路径,但当前目录中没有任何更改。@a.Mohsen-Hmmm<代码>我创建了一个名为“testdir”的文件!档案?您不能将cd
放入文件中。你是说目录吗?无论如何-您可能正在另一个目录中运行程序,而不是您认为的s=f[2]
它应该是s=f[1]
。但无论如何,您可能只想在中使用并在[2]
中编写s=&in,您也可以说cd这是我的花式目录名
如何验证程序的结果?我很想相信您可能不知道POSIX环境中当前目录的定义——它是正在运行的进程的属性。您的程序和从中运行它的shell都有自己的cwd。子进程无法更改父进程的属性。