我正在尝试用 C 语言制作自己的 shell。它使用一个管道,并且输入(目前)是静态的。我使用 execvp 执行命令。
一切都很好,除了当我运行命令 ls |grep ".c"
时没有得到任何结果。谁能告诉我问题出在哪里并找到解决方案。
到目前为止的 shell :
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int p[2];
int pid;
int r;
main()
{
char *ls[] = {"ls", NULL};
char *grep[] = {"grep", "\".c\"", NULL};
pipe(p);
pid = fork();
if (pid != 0) {
// Parent: Output is to child via pipe[1]
// Change stdout to pipe[1]
dup2(p[1], 1);
close(p[0]);
r = execvp("ls", ls);
} else {
// Child: Input is from pipe[0] and output is via stdout.
dup2(p[0], 0);
close(p[1]);
r = execvp("grep", grep);
close(p[0]);
}
return r;
}
最佳答案
删除 grep 参数中的引号。即,使用
char *grep[] = {"grep", ".c", NULL};
如果您调用 execvp
,通常的 shell 参数扩展(即通配符、删除引号等)不会发生,因此实际上您正在做的事情与
ls | grep '".c"'
在普通 shell 中。
还要注意,调用 execvp
之后的任何内容都不会执行,execvp
替换当前进程,它永远不会返回。
关于c - LS |用 C 语言编写的 shell 中的 grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926804/