Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

process - Implement shell by using fork() and execvp() in c++

I'm implemented shell by using fork() and execvp(), however, the args[0] didn't store any data from the buffer, and also the args, I don't know what that is, and it returns me an address. execvp prototype should be (char* argument, char* argument); at this point, it supposed to execute one command and return the PID of the child process

#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
");
    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)
 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;
    }
question from:https://stackoverflow.com/questions/65843028/implement-shell-by-using-fork-and-execvp-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...