首页 > 解决方案 > 自定义 shell 无法识别传递给它的最后一个命令

问题描述

我正在尝试实现一个自定义的 Unix shell,但是,传递给它的最后一个命令永远无法识别。当我运行“ls”时,没有任何反应,但如果我执行“ls ls”,它就像只通过了一个 ls,或者如果我执行“ls -o”,它只执行“ls”,但如果我执行“ls - o -o” 它执行“ls -o”,它的功能应该类似于标准的 Unix shell。

#include "apue.h"
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int parse(char* buf, char **cmds);
static void sig_int(int);       
int
main(void)
{


    char *path;
        path = getenv("PATH");
    char    buf[MAXLINE];   
     char *envp[] = {path, NULL};
    pid_t   pid;
    int     status;
    char *command[MAXLINE];
    char *input; 
    if (signal(SIGINT, sig_int) == SIG_ERR)
        err_sys("signal error");
    printf("%% "); 
    while (fgets(buf, MAXLINE, stdin) != NULL) {
            parse(buf, command);





        if ((pid = fork()) < 0) {
            err_sys("fork error");
        } else if (pid == 0) {      /* child */

            input = command[0];
            execvpe(input, command, envp);
            err_ret("couldn't execute: %s", buf);
            exit(127);
        }

        /* parent */
        if ((pid = waitpid(pid, &status, 0)) < 0)
            err_sys("waitpid error");
        printf("%% ");

            }
    exit(0);

}

/*parses input into something runable*/
int parse(char* buf, char **cmds)
{
    char *sep;
    int count;
    count = 0;
    while((sep = strchr(buf, ' ')))
    {
        cmds[count]= buf;
        *sep = '\0';
        buf = sep +1;
        count++;
        while (*buf && (*buf == ' ')) /* Ignore spaces */
                    buf++;
    }
    cmds[count] = NULL;
    if(count == 0)
        return 1;
    return 0;
}

标签: c

解决方案


推荐阅读