程序在execvp(command.argv [0],command.argv) [英] program stops after execvp( command.argv[0], command.argv)
问题描述
我正在写一个小的shell程序,它接受一个命令并执行它。如果用户输入无效的命令,if语句返回-1。如果命令正确,它执行命令,但是一旦它执行命令程序结束。我做错了什么是不执行代码行之后呢?我已经测试execvp(command.argv [0],command.argv)与ls和cat命令,所以我很确定它的工作原理。这里是我的代码。
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()函数系列用
a替换当前的过程映像
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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!