我必须使用系统调用fork()/ execvp()在C中开发一个简单的shell.到目前为止,我的代码接受一个命令,使用strtok将其拆分为数组argv然后我调用fork来创建子进程并执行命令.我在ubuntu上工作,其中大多数命令都在/ bin /目录中,所以我附加程序名称(例如/ bin/ls)并将其用于execvp的第一个arg然后我给它argv数组.如果我输入命令"ls",我的程序可以工作,但是当尝试其他命令甚至"ls -l"时,我会得到一个"ls:invalid选项".我不知道我在这里做错了什么.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_LEN 1024
int main(){
char line[BUFFER_LEN]; //get command line
char* argv[100]; //user command
char* path= "/bin/"; //set path at bin
char progpath[20]; //full file path
int argc; //arg count
while(1){
printf("My shell>> "); //print shell prompt
if(!fgets(line, BUFFER_LEN, stdin)){ //get command and put it in line
break; //if user hits CTRL+D break
}
if(strcmp(line, "exit\n")==0){ //check if command is exit
break;
}
char *token; //split command into …Run Code Online (Sandbox Code Playgroud)