【发布时间】:2015-01-13 00:56:11
【问题描述】:
我需要一些关于类的简单 shell 的帮助,但我担心我不太了解 execvp() 函数的工作原理。
shell 不做太多事情,不支持管道、重定向、脚本或任何类似的东西。它只读取一个命令,读取选项(命令作为选项[0]),然后分叉。
它工作了几次,然后开始给我关于无法找到命令的错误。此处发布的其他类似问题与管道或重定向有关。
请原谅noobcode,它不漂亮,但我希望它清晰:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#define OPT_AMT 10
const size_t SIZE = 256;
int i = 0;
int o = 0;
int main(void) {
// initializing data
int exit = 0;
char cwd[SIZE];
char cmd[SIZE];
char input[SIZE * OPT_AMT];
char *opt[OPT_AMT];
getcwd(cwd, SIZE);
// main loop
while (exit == 0) {
// reset everything
o = 1;
i = 0;
cmd[0] = "\0";
while (i < OPT_AMT) {
opt[i++] = "\0";
}
// get input
printf("%s $ ", cwd);
scanf("%s", cmd);
gets(input);
opt[0] = cmd;
char *t = strtok(input, " ");
while (t != NULL) {
opt[o++] = t;
t = strtok(NULL, " ");
}
// if exit, exit
if (strcmp(cmd, "exit") == 0) {
exit = 1;
}
// else fork and execute
else {
pid_t pID = fork();
if (pID == 0) { // child process
execvp(cmd, opt);
} else if (pID < 0) { // failed to fork
printf("\nFailed to fork\n");
} else { // parent process
wait(0);
}
}
}
// cleanup
printf("\nFinished! Exiting...\n");
return 0;
}
有什么明显的错误吗?我最近添加了退出条件和重置选项数组。
另外,这是我的第一个问题,所以请提醒我我可能违反的任何规则。
【问题讨论】:
-
不要使用
gets()。它本质上是不安全的,它甚至不再是 C 的一部分。请改用fgets(),如有必要,不要忘记删除末尾的换行符。