linux - execvp:执行 ls 命令时 - 出现错误“ ls: 无法访问 /etc : 没有这样的文件或目录”
下面的函数接受一个 char 指针数组,例如: arr[0]: LS arr[1]:-l arr[2]:-a arr[3]:/etc arr[4]:NULL /* 由于 execvp 期望末尾为 NULL */
// 函数调用是 runCmd(arr);
函数定义如下:
void runCmd(char *arr[]){
pid_t child_pid,tpid;
int child_status;
child_pid = fork();
if(child_pid == 0){
/* The child process executes the exec*/
execvp(arr[0],arr);
/*if it returns it must have failed */
fflush(stdout);
printf("Unknown Command \n");
exit(0);
}
else {
/* let the parent wait for the child */
do{
tpid = wait(&child_status);
}while(tpid != child_pid);
}
}
执行后我收到消息 -
ls: cannot access /etc
: No such file or directory
The below function takes in a array of char pointers Eg :
arr[0]: ls
arr[1]: -l
arr[2]: -a
arr[3]: /etc
arr[4]:NULL /* Since execvp expects a NULL at the end */
// function call is runCmd(arr);
the function definition is below :
void runCmd(char *arr[]){
pid_t child_pid,tpid;
int child_status;
child_pid = fork();
if(child_pid == 0){
/* The child process executes the exec*/
execvp(arr[0],arr);
/*if it returns it must have failed */
fflush(stdout);
printf("Unknown Command \n");
exit(0);
}
else {
/* let the parent wait for the child */
do{
tpid = wait(&child_status);
}while(tpid != child_pid);
}
}
After executing I get the message -
ls: cannot access /etc
: No such file or directory
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您正在阅读命令并忘记删除尾随换行符,导致您的
ls
尝试列出目录"/etc\n"
。Looks like you are reading in the command and forgetting to strip the trailing newline, causing your
ls
to try and list the directory"/etc\n"
.