C - 在基本shell

时间:2016-02-11 23:34:09

标签: c linux shell pipe

我试图在我编写的基本shell中实现一个管道命令的功能。到目前为止,我可以执行单个命令,并且我已经查看了如何管道命令的示例,但我不确定如何在我的代码中实现它。我希望能够在必要时执行单个命令以及管道命令,并且我不确定需要进行哪些修改。

我尝试将commandexec()分成两个独立的函数,一个用于源,另一个用于目标,但后来我不确定如何执行单个命令(无管道)。如果这是一个更好的起点,我也有这个代码。

这是我的原始代码:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

/*Function Prototypes*/
void commandparser(char *line, char **argv);
int commandexec(char **argv);

int main()
{
    char line[1000]; //input line
    char *argv[25]; //command line arguments

    while (1) //repeat until finished
    {
        printf("Shell: "); //the prompt that will be displayed
        if(fgets(line, 1000, argv) == NULL)//read commands and break if there is nothing
        {
            break;
        }
        printf("\n");

        commandparser(line, argv);

        if(commandexec(argv) == 0) //execute the command
        {
            break;
        }

        if (strcmp(argv[0], "exit") == 0) //check if user wants to exit
        {
            exit(0); //exit
        }
    }
}

void commandparser(char *line, char **argv)
{
    const char *delimeter = " "; //where to split the commands
    int i = 0;
    for(; i < argv; i++)
    {
        argv[i] = strtok(&line, delimeter); //split commands by delimeter

        if(argv[i] == NULL)//if there are no commands then it breaks
        {
            break;
        }
    }
}

int commandexec(char **argv)
{
    pid_t pid = fork(); //fork process
    int child;

    if (pid == 0) //begins the child process
    {
        execvp(argv[0], argv); //this will execute the command

        char *err = strerror(errno);
        printf("Shell: %s %s\n", argv[0], err); //error message

        return 0;
    }
    else if (pid == -1) //checks for error
    {
        char *err = strerror(errno);
        printf("%s\n", err);

        return 1;
    }
    else
    {
        waitpid(pid, &child, 0); //this will wait for child to finish

        return 1;
    }
}

0 个答案:

没有答案