我正在用 C 语言编写一个简单的 shell。用户输入命令,它们存储在二维数组中,例如:
SHELL$ ls ; date ; ls
// This is parsed into the following
char* commands[1000] = {"ls", "date", "ls"};
如果在整个程序中我没有该输入的特定角色,我有一个 for 循环,它将数组的每个元素传递到系统 - 我没有 ls 和 date 的特定角色:
if (did_not_process == 0)
system(commands[i]);
现在我想将 system() 转换为 execvp() 并具有完全相同的功能。这是我的方法,但效果不佳:
if (did_not_process == 0) {
command[0] = commands[i];
command[1] = NULL;
if (fork() == 0) {
execvp(command[0], command);
} else {
wait(NULL); //wait for child to complete?
}
}
唯一的问题是,当我进一步迭代 shell(一个简单的 while 循环)时,它会偶尔且无法控制地打印执行结果。问题出在我所展示的代码中的某个地方,但我无法弄清楚哪里。
这是示例输出:
SHELL$ ls;date;ls
file
Mon Jul 16 13:42:13 EDT 2012
file
SHELL$ ls
SHELL$ file
第一次工作,然后在与 shell 输入相同的行上打印文件。
最佳答案
仅根据一般原则,您应该检查系统调用的返回值是否有错误:
int cpid = fork()
if (cpid == -1) {
perror("fork");
} else if (cpid == 0) {
execvp(command[0], command);
perror("execvp");
_exit(1);
} else {
if (waitpid(cpid, 0, 0) < 0)
perror("waitpid");
}
关于C shell 程序中从 system() 更改为 execvp(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11509664/