首页 > 解决方案 > 在 c++ 中使用 fork() 和 execvp() 实现 shell

问题描述

我使用 fork() 和 execvp() 实现了 shell,但是,args[0] 没有存储缓冲区中的任何数据,还有 args,我不知道那是什么,它返回给我一个地址。execvp 原型应该是(char* 参数,char* 参数);此时,它应该执行一个命令并返回子进程的PID

#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

using namespace std;

int main(int argc, char *argv[])
{
  char buffer[10][500];
  char *args[50]; //aurgument list for execvp()
  string input;
  cout <<"myshell$";
  getline(cin,input);
  int k = 0;
  int counter = 0;

  //first edit on input
  //splite string into char in 2D array list buffer
  for (char i : input){ //splite into char in buffer
    buffer[counter][k] = i;
    k++;
  if(i == '|') //multiph command
    counter++;
  }

 
 //second edit
 //assigned pointer to the buffer
 int pos = 0;
 for(int i = 0 ; i < 50; i++){
   args[i] = (char*)&buffer[0][pos];
   pos += strlen(args[i]) + 1; //point to next token
    cout << args[i] << ", ";
    }
  args[50] = (char*)nullptr;// end the argument list
  int pos = 0;
  int rc = fork(); //
  if (rc < 0){ // fork creation fail
    perror("fork failed\n");
    return 1;
  }
  if(rc == 0){//child process
    int status_code = execvp(args[0], args);
    cout << "1: " << args[0][0] << endl;
    cout << "2: " << args << endl;
    if(status_code == -1){ //error handling
      perror("Child process terminated fail");
      return 1;
    }
     else{ // terminated correct
     printf("process (pid:%d)\n exit with 0", (int) getpid());
    }
    }else{ //parent process
      int rc_wait = wait(NULL);
      printf("parent process,(rc_wait:%d)", rc_wait);
    }

     cout << endl;
      return 0;
    }

标签: c++processfork

解决方案


推荐阅读