c++ - 如何在指定文件路径上的程序中使用 ls?

标签 c++ ls execv

为项目创建我自己的 shell 程序。目前正在尝试 fork() 然后执行 execv(),方法是发送执行 ls 的位置,然后发送 ls 的参数,即文件路径和选项。

到目前为止,ls 输出只显示了我的 shell 程序所在目录中的内容。

// directoryPath[] is  /home/pi/cs460
// option[] i use NULL or -al for the time being
void lsProcess(char directoryPath[], char option[])
{
    string lsLocation = "/bin/ls";
    char * lsPlace = new char[lsLocation.size() + 1];
    strcpy(lsPlace, lsLocation.c_str());

    char * args[] = {lsPlace, NULL, directoryPath};

    execv(args[0], args);
    exit(0);
}

最佳答案

不应该 char * args[] = {lsPlace, NULL, directoryPath};char * args[] = {lsPlace, directoryPath, NULL};?当 ls 解析您的参数数组时,它会在 args[1] 处命中 null 并停止解析。此外,您可能应该验证 directoryPath 是否以 null 终止...

编辑

如果你想要一个options的占位符,你需要包含一个只包含null的元素数组来表示一个空字符串,然后在最后添加另一个null

char options[1];
options[0] = 0;

char * args[] = {lsPlace, options, directoryPath, NULL};

关于c++ - 如何在指定文件路径上的程序中使用 ls?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55603317/

相关文章:

c++ - 使用 C++ 设置对目录的权限

c++ - 将调用线程置于可警告等待状态

c - 指针失去其值+ execv 编译警告

c - 在子进程中执行文件

c - 如何立即从 Linux 中的 fork 子进程返回?

c++ - 下面的字符串循环缓冲区实现有哪些可能的改进?

python - 运行命令 : ls -l . '{' 不被识别为内部或外部命令、可运行程序或批处理文件

bash - Linux : The command ls -la shows a file pointing to another file. 是什么意思?

C 编程 : ls function sort by file, 可执行文件和目录

c++ - 对象 'X' 已经存在