为项目创建我自己的 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/