【发布时间】:2020-03-29 16:17:21
【问题描述】:
cd 命令有问题。其他一切似乎都有效,例如编译和运行程序,以及ls。我运行ls、ls -1 并且工作得很好。当我运行 cd 或 cd Desktop 时,没有任何反应。
我正在创建一个 fork,然后执行一个进程。我退出 exit 或按 CTRL+D。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#define SIZE 255
void printPrompt(){
printf("\nuser@shell > "); //print prompt
}
void readPrompt(char string[],int *check){ //read prompt line from user
if( (scanf(" %[^\n]",string)==EOF) ){
//printf("\nTEST\n");
*check=0;
}
printf("\n");
}
void RunSimple(char line[]){ //creating a fork and running a program with exe fuction.
char **args=malloc(8 * sizeof(char *));
char *parsed;
int i=0,pid;
parsed = strtok(line," ");
while (parsed != NULL) {
args[i] = parsed;
i++;
parsed = strtok(NULL," ");
}
pid = fork();
if(pid == 0){
execvp (args[0],args);
}
waitpid(pid,NULL,0);
}
int main(int argc, char **argv){
char line[SIZE];
int check=1;
while(1){
printPrompt();
readPrompt(line,&check);
if( (!strcmp(line,"exit")) || (check==0) ){
break;
}
RunSimple(line);
}
}
谢谢。
【问题讨论】:
-
您可能会发现,任何仅用于移动文件或将内容输出到
stdout或stderr的命令都可以正常工作,但改变环境状态的命令则不行。一个分叉的进程获得了父环境的副本,从那时起就不能影响父环境——例如,参见stackoverflow.com/questions/9360679/…。 -
您的父进程必须执行
cd。您不能在子 shell 中使用cd,因为它不会更改父 shell 中的路径。例如,请参阅Why doesn't the cd command work in my shell program?、How can I implement cd command in my own shell in C?、How to implement your own cd command in your own shell、Why doesn't “cd” work in a shell script? 等。 -
我也不允许使用为运行命令(如 /bin/sh)和函数 system() 创建新 shell 的函数。所以我猜想运行 cd 命令是不可能的。