程序在 execvp(command.argv[0], command.argv) 后停止

2022-01-11 00:00:00 operating-system c++ execvp

我正在编写一个小 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 :) :)

相关文章