【问题标题】:Using execve() to write the ls program in UNIX在 UNIX 中使用 execve() 编写 ls 程序
【发布时间】:2012-04-12 18:36:00
【问题描述】:

在高层次上,您将如何使用 execve() 函数在 UNIX 中编写 ls 程序的副本?我正在做一个练习来熟悉 exec() 系列函数、命令行参数和环境变量。我不熟悉使用这些概念,但我知道它们的作用。

【问题讨论】:

  • 你根本不会使用 exec,除非你想打电话给 ls 为你做这项工作。

标签: c unix exec argv ls


【解决方案1】:

下面的代码可以执行ls命令。你是这个意思吗?

#include <stdio.h>

int main(void)
{
        system("ls");
        return 0;
}

我为你写了一个简单的ls 演示。

my_ls.c

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
        if (argc != 2) {
                return 0;
        }

        DIR *dir = opendir(argv[1]);
        if (dir) {
                struct dirent *s_dir;
                while((s_dir = readdir(dir))) {
                        printf("%s ", s_dir->d_name);
                }
                printf("\n");
        }

        return 0;
}

用法:

gcc my_ls.c -o my_ls
./my_ls .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 2014-07-29
    相关资源
    最近更新 更多