我正在尝试制作一个调用 ls
的程序和 grep
使用 exec
的系统调用.具体来说,我必须执行 ls > tmp; grep -c pattern < tmp
为了计算满足模式的文件数量。如您所见,我将 ls 的内容保存在 tmp 文件中,然后我想使用 grep 来统计文件。
让我们假设 pattern = txt
.我正在尝试类似以下代码的操作:
char *a = "ls > tmp";
char *b = " -c ";
char *fin = " < tmp";
char *comanda;
if((comanda = malloc(strlen(pattern)+strlen(pattern)+1)) != NULL){
comanda[0] = '\0'; // ensures the memory is an empty string
strcat(comanda,b);
strcat(comanda, pattern);
strcat(comanda,fin);
} else {
return -1;
}
ret = execl("/bin/sh","sh","-c",a,NULL);
ret = execl("/bin/sh","sh","-c",comanda, NULL);
但它向我显示以下错误:ls: cannot access > tmp: No such file or directory
.所以我不知道如何获取 grep
的值,因为 execl
函数不返回值,那么我怎样才能实现 grep
值(value)?
最佳答案
要获取命令的输出,您需要使用管道。
看看:Connecting n commands with pipes in a shell?
你可以这样做:
ls | grep -c pattern
如果您只想获取文件名中具有特定模式的文件,您可能需要使用 find
find your_path/ -name "*pattern*" | wc -l
看看Grabbing output from exec获取execl的输出
这是一个例子,将execl的第4个参数替换成任何你想要的:)
( execl("/bin/sh", "sh", "-c", "ls > tmp; grep -c 'pattern' < tmp", (char *)NULL);
)
#include <unistd.h>
#include <string.h>
int main()
{
int fd[2];
pipe(fd);
if (fork() == 0)
{
close(fd[0]);
dup2(fd[1], 1);
dup2(fd[1], 2);
close(fd[1]);
execl("/bin/sh", "sh", "-c", "find your_path -name '*pattern*' | wc -l", (char *)NULL);
}
else
{
char buffer[1024] = {0};
close(fd[1]);
while (read(fd[0], buffer, sizeof(buffer)) != 0)
{
write(1, buffer, strlen(buffer));
memset (buffer, 0, sizeof(buffer));
}
}
return 0;
}
关于c - 使用 execl 获取 grep 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40787973/