使用 execl 运行 Linux 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13506267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:50:35  来源:igfitidea点击:

Using execl to run a Linux command

clinuxunixexec

提问by femchi

I need to list all files in the current directory which have a permission of 644 by writing a C language program. I can not use system()and have to use execl()in order to use system calls.

我需要通过编写一个C语言程序列出当前目录中所有权限为644的文件。我不能使用system()并且必须使用execl()才能使用系统调用。

This a line that I used in my code:

这是我在代码中使用的一行:

execl("/usr/bin/find", "find . -maxdepth 1 -perm 644", (char *)NULL);

The problem is that the code is searching the whole disk instead of the current directory. Would you help me to fix it please?

问题是代码正在搜索整个磁盘而不是当前目录。请你帮我修好吗?



        ...

        case 4:
            int status;
            switch (fork()){
                case -1: quit ("fork",1);
                case 0:
                execl("/usr/bin/find","find","." ,"-maxdepth" ,"1","-perm", "644",(char *)NULL) ;
                exit (200);
                default:
                wait(&status);
                exit(0);
            }
        }

采纳答案by Jonathan Leffler

Separate the arguments:

分隔参数:

execl("/usr/bin/find", "find", ".", "-maxdepth", "1", "-perm", "644", (char *)NULL);

Your invocation was equivalent to invoking the findprogram with no arguments (and a very funny argv[0]).

您的调用相当于调用find没有参数的程序(并且非常有趣argv[0])。

回答by alinsoar

execl("/usr/bin/find","/usr/bin/find",  ".", "-maxdepth", "1", "-perm", "0644",(char *)NULL);

回答by mvp

For your particular task, using file tree walk(ftw) is more appropriate.

对于您的特定任务,使用文件树遍历( ftw) 更合适。

ftw is just a library, so you don't need to spawn external process to get job done. Also, it is much easier to parse results.

ftw 只是一个库,因此您无需生成外部进程即可完成工作。此外,解析结果要容易得多。