c - 使用 execl 获取 grep 值

标签 c linux bash shell grep

我正在尝试制作一个调用 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/

相关文章:

字符常量对于它的类型来说太长

mysql - Wheezy 上的 GitLab,安装 Gems 时出错,libmysqlclient-dev 可能丢失但无法安装

linux - "host1$ ssh host2 cmd1 | cmd2"cmd2 将在哪台主机上运行?

regex - Linux : Replace key-value pair, 值包含文件路径

c - 程序中有什么错误?

c - 使用 C 中的 fscanf 读取 .txt 文件

linux - Qt的可链接报告库,带有编辑器或简单标记

python - Virtualenv 存在但无法从 bash 脚本访问它

c - C中的交换指针

c++ - 从 Linux 中的多个非阻塞命名管道读取