如何解决c++中使用fork()和execvp()实现shell
我使用 fork() 和 execvp() 实现了 shell,但是,args[0] 没有存储来自缓冲区的任何数据,还有 args,我不知道那是什么,并且它返回给我一个地址。 execvp 原型应该是 (char* argument,char* argument);此时,它应该执行一个命令并返回子进程的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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。