c++ - 在 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;
}
解决方案
推荐阅读
- xcode - 在 xcode 11.5 中构建颤振项目时找不到 grpc/grpc.h 文件错误
- c#-4.0 - 如何允许类仅从两个接口之一继承
- cron - 用氮气生成随机壁纸的简单 cron 作业
- apache-spark - Spark PySpark 以一列值作为键输出 JSON
- flutter - 带有继承类的颤振飞镖JsonSerializable
- python - 在 pandas Python 中读取大表的有效方法是什么?
- stata - 你能划分两个表的条目吗?
- laravel - 如何添加“或”条件来调用 Laravel 路由上的中间件?
- python - Pandas 从 12 个 excel 文档导入 - FileNotFoundError: [Errno 2] No such file or directory: 'x'
- file - Fortran 打开一个名称可更改的“.dat”文件