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

问题描述 投票:0回答:1

为项目创建自己的shell程序。目前正在尝试使用fork(),然后通过发送执行ls的位置执行execv(),然后发送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);
}
c++ ls execv
1个回答
2
投票

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

编辑

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

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

char * args[] = {lsPlace, options, directoryPath, NULL};
© www.soinside.com 2019 - 2024. All rights reserved.