我试图用C制作自己的shell。它使用一个管道,并且输入(目前)是静态的。我使用execvp执行命令。一切都很好,除了我运行命令时ls |grep ".c"
没有任何结果。谁能告诉我问题出在哪里并找到解决方案。
到目前为止的外壳:
#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扩展(即,globbing,引号的删除等),因此实际上,您在做什么与
ls | grep '".c"'
在普通的外壳中。
另外请注意,调用to之后execvp
不会执行任何操作,它将execvp
替换当前进程,它将永远不会返回。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句