【问题标题】:execl() find command cexecl() 查找命令 c
【发布时间】:2013-12-13 15:29:55
【问题描述】:

我想在 shell 中执行 find 命令来只打印 *.c 文件 然后返回带有文件的字符串并将其打印到标准输出。 我正在使用管道来做到这一点。当我尝试运行时,我总是得到find failed: No such file or directory

我认为问题在于路径。 我应该给它的路径是home/username/Downloads,以防我想打印我的下载文件夹中存在的所有 *.c 文件??

#include <stdio.h>
#include <stdlib.h>


int main(int argc, char ** argv){
   int fds[2];
   char buffer[4096];

   if(pipe(fds) == -1){
      perror("pipe creation failed");
      exit(1);
   }

   switch (fork()){

    case 0://child
       close(fds[0]);
       execl("usr/bin/find","find","home/username/Downloads", "-name \"*.c\" -print0",NULL);
       perror("find failed");
       exit(20);
       break;

      case -1: //fork failure
       perror("fork failure");
       exit(1);

      default: //parent
       close(fds[1]); //close stdin so only can do stdout
       int size= read(fds[0],buffer, 4096);
       printf("%s",buffer);
   }

   exit(1);
}

【问题讨论】:

  • argv[0] 是程序名而不是程序的第一个参数
  • 好吧,你是对的。我现在编辑
  • 你应该使用 glob() 函数。另见 readdir() 或 stat()
  • home/username/Downloads前面不应该有斜线吗?还是home 是您的程序运行所在目录中的一个目录?
  • @squeamish 前面 usr/bin/find 一样

标签: c linux find exec


【解决方案1】:

usr/bin/find前面少了一个斜杠,所以find只有在工作目录为/时才会执行

【讨论】:

  • 使用 dup() 或 dup2() 重定向 find 的标准输出
【解决方案2】:

我建议将单独的参数作为单独的参数传递:

    execl("/usr/bin/find", "find", 
      "/home/username/Downloads", 
      "-name",
      "*.c", /* As no shell is invoked no quotation marks are needed to protect the *. */
      "-print0",  
      (char *) NULL);

【讨论】:

  • 你能帮我打印一下结果吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-21
  • 2013-04-07
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多