program stops after execvp( command.argv[0], command.argv)(程序在 execvp(command.argv[0], command.argv) 后停止)
问题描述
我正在编写一个小 shell 程序,它接受一个命令并执行它.如果用户输入了无效命令,则 if 语句返回 -1.如果命令是正确的,它就会执行命令,但是一旦它执行了命令,程序就会结束.我做错了什么是不执行它之后的代码行?我已经用 ls 和 cat 命令测试了 execvp(command.argv[0], command.argv),所以我很确定它可以工作.这是我的代码.
I am writing a small shell program that takes a command and executes it. If the user enters a not valid command the if statement returns a -1. If the command is correct it executes the command, however once it executes the command the program ends. What am I doing wrong that is does not execute the lines of code after it? I have tested execvp( command.argv[0], command.argv) with ls and cat commands so I am pretty sure it works. Here is my code.
int shell(char *cmd_str ){
int commandLength=0;
cmd_t command;
commandLength=make_cmd(cmd_str, command);
cout<< commandLength<<endl;
cout << command.argv[0]<< endl;
if( execvp( command.argv[0], command.argv)==-1)
//if the command it executed nothing runs after this line
{
commandLength=-1;
}else
{
cout<<"work"<<endl;
}
cout<< commandLength<<endl;
return commandLength;
}
推荐答案
来自 手册页 execvp(3)
exec() 系列函数将当前进程映像替换为一个新的过程映像
The exec() family of functions replaces the current process image with a new process image
因此,您当前的进程映像将被您的命令映像覆盖!因此,您需要始终使用 fork+exec
组合,以便您的命令在子进程中执行,并且您当前的进程作为父进程安全地继续!
So your current process image is overwritten with the image of your command! Hence you need to use a fork+exec
combination always so that your command executes in the child process and your current process continues safely as a parent!
我想用一张图片来说明问题,因为一张图片能说出一千个单词.无意冒犯:) :)
On a lighter note I want to illustrate the problem with a picture as a picture speaks a thousand words. No offence intended :) :)
这篇关于程序在 execvp(command.argv[0], command.argv) 后停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:程序在 execvp(command.argv[0], command.argv) 后停止
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01