如何修复简单外壳的输出

问题描述

我的 shell 程序当前正在接受 ls 命令,但返回了错误输出。我注意到的另一个问题是我的 shell 没有删除输入的前一行。当我输入 ls 时,它会返回我的文件,但是如果我再次输入 ls,shell 仍会保存我之前的命令。

我的输出:在 (exitstatus) 之前需要 [* cmd *] 并且不应该有 [ -a ]

shell> ls -a
[ ls ] [ -a ] (PID: 1101501) //pid's will be different
.  ..  Exec  Exec.c  Shell  Shell.c  String  StringMalloc.c //content will be different
(Exit: 0)

预期输出

shell> ls -a
[ ls ] (PID: 3052378)
.             Descr.c                       MallocLab
..            Dest.txt                      Midterm.txt
a             Dir                           Notes
...
[* ls *] (Exit: 0)

代码

    const int MAXLINE = 80;
    const int MAX_ARGS = 5;
    char buffer[MAXLINE];
    char* args[MAX_ARGS];
    char* p;
    int i = 0;
    pid_t pid;
    int arg;
while(1)
    {
        printf("shell> ");
        if(!fgets(buffer,MAXLINE,stdin)){break;}
        p = strtok(buffer,",\n");
        while(p != NULL)
        {
            args[i] = p;
            p = strtok (NULL,\n");
            ++i;
        }
        args[i] = NULL;

        arg = i;
        for(i = 0; i < arg; ++i)
        {
            printf("[ %s ] ",args[i]);
        }
        printf("(PID: %d)\n",getpid());
        

        for(i = 0; i < strlen(buffer); ++i)  /*I'm assuming the line deleting is in here*/
        {
            if(buffer[i] == '\n')
            {
                buffer[i] = '\0';
            }
        }

        pid = fork();

        if(pid == 0)
        {
            int ret = execvp(args[0],args); 
            if(ret < 0)
            {
                fprintf(stderr,"exec error (%s) -- exiting\n",strerror (errno));
                exit (1);
            }
        }

        if(pid > 0)
        {
            wait(NULL);
            fprintf("[* %s *] ",args);  /*not sure how to get [* cmd *] in output*/
            fprintf("(Exit: %d)\n",errno);
        }
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)