使用fork/execvp在C中编写一个简单的shell

C11*_*116 9 c linux bash shell execvp

我必须使用系统调用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 separate strings
    token = strtok(line," ");
    int i=0;
    while(token!=NULL){
        argv[i]=token;      
        token = strtok(NULL," ");
        i++;
    }
    argv[i]=NULL;                     //set last value to NULL for execvp

    argc=i;                           //get arg count
    for(i=0; i<argc; i++){
        printf("%s\n", argv[i]);      //print command/args
    }
    strcpy(progpath, path);           //copy /bin/ to file path
    strcat(progpath, argv[0]);            //add program to path

    for(i=0; i<strlen(progpath); i++){    //delete newline
        if(progpath[i]=='\n'){      
            progpath[i]='\0';
        }
    }
    int pid= fork();              //fork child

    if(pid==0){               //Child
        execvp(progpath,argv);
        fprintf(stderr, "Child process could not do execvp\n");

    }else{                    //Parent
        wait(NULL);
        printf("Child exited\n");
    }

}
} 
Run Code Online (Sandbox Code Playgroud)

Iha*_*imi 7

无效选项是因为fgets()保持'\n'按Enter键的时候,试试这个

if(!fgets(line, BUFFER_LEN, stdin))
    break;
size_t length = strlen(line);
if (line[length - 1] == '\n')
    line[length - 1] = '\0';
Run Code Online (Sandbox Code Playgroud)

当你试图打电话时,ls -l"-l\n"作为选项传递,因此消息.

你必须改变

strcmp(line, "exit\n")
Run Code Online (Sandbox Code Playgroud)

strcmp(line, "exit")
Run Code Online (Sandbox Code Playgroud)