我是C的新手,我在OS类中,我需要在C(yay)中编写一个基本的shell.它实际上已经过了一半,我只是想在完成工作的同时学习C语言.
我试图在分叉后使用exec,现在调用mkdir.我需要通过一点点论证,但我一直想弄清楚,并希望有人能告诉我哪里出错了.
} else {
//fork exec
int pid = fork();
if (pid == 0) {
printf("%s",my_argv[0]);
execve("/bin/mkdir",my_argv,0);
} else wait(NULL);
}
Run Code Online (Sandbox Code Playgroud)
这是我响应mkdir调用的部分.现在,我有一个从用户输入的行[],该命令被使用
command = strtok(line, DELIMITERS);
Run Code Online (Sandbox Code Playgroud)
arg是:
arg = strtok(0,DELIMITERS);
my_argv[0] = arg;
Run Code Online (Sandbox Code Playgroud)
一切都很好,但mkdir永远不会工作.打印my_argv [0]给出了我期望的正确参数.我确定这是一个愚蠢的东西,但任何提示将不胜感激.
所有代码:
int main(int argc, char *argv[])
{
char *command;
char line[MAXLINE];
char *arg = NULL;
char *my_argv[];
while(1) {
printf(PROMPT);
if (fgets(line,MAXLINE,stdin) != NULL) {
//take out \n
line[strlen(line)-1] = '\0';
}
//looks for first delimiter, saves as the command
command = strtok(line, DELIMITERS);
//start looking at what command it is by comparing
if (strcmp(command,"cd")==0) {
//if they equal zero, they match
//this is a cd command, must have following arg
if (argv[1] == NULL) chdir("/");
else chdir(argv[1]);//chdir is the system call for cd
} else if (strcmp(command,"exit")==0) {
break;
} else if (strcmp(command,"mkdir")==0){
arg = strtok(0,DELIMITERS);
my_argv[0] = arg;
my_argv[1] = NULL;
if (!arg) {
printf("Usage: mkdir missing arg\n");
} else {
//fork exec
int pid = fork();
if (pid == 0) {
printf("%s",my_argv[0]);
//mkdir(arg);
execve("/bin/mkdir",my_argv,0);
} else wait(NULL);
}
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2653 次 |
| 最近记录: |