【发布时间】:2013-09-07 07:54:48
【问题描述】:
我正在尝试编写一个 shell。但是我的 shell 不执行命令 - ls -l |较少的。我正在使用 execvp。代码如下。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(){
int pid, status, num, len;
char str[1000], cwd[100];
char* word[100];
getcwd(cwd, sizeof(cwd));
while(1){
chdir(cwd);
printf("%s > ", cwd);
gets(str);
pid=vfork();
if(pid == 0){
num = 0;
word[num] = strtok (str, " ");
while (word[num] != NULL) {
word[num] = strdup (word[num]);
len = strlen (word[num]);
if (strlen (word[num]) > 0)
if (word[num][len-1] == '\n')
word[num][len-1] = '\0';
word[++num] = strtok (NULL, " ");
}
if(strcmp(word[0], "cd") == 0){
chdir(word[1]);
getcwd(cwd, sizeof(cwd));
}
else{
execvp(word[0],word);
}
exit(0);
}
else{
wait(&status);
}
}
return 0;
}
【问题讨论】:
-
据我所知,
|是一个与 shell 相关的令牌。在 shell 之外做这件事并没有真正起作用,因为它的 shell 读取|并让魔法发生。没有外壳来实现神奇的管道......它不起作用。 -
那么我还有其他方法可以运行|吗?我可以以某种方式将字符串和蛮力使它工作
-
@Cornstalks 说得真切。
execvp用于执行带有一组参数的命令(如果需要)。你可以试试system来调用一个成熟的shell命令行。 -
在您使用
vfork()之前,请阅读您可以在子进程中执行的操作。我不认为chdir()或getpwd()是允许的。请改用fork()。这可能不是你的主要问题(目前),但要非常非常小心vfork()的限制。
标签: c linux shell exec systems-programming