用C编程shell

Req*_*iem 0 c unix shell

我目前正在用C语言编写一个shell,我遇到了一些问题.例如,当我尝试将我的命令与"退出"进行比较时,它只是对它进行写操作,并且根据gdb它们的行为不相同.我以段错误结束.如果有人能帮我弄清楚什么是错的,我会非常感激.这是我的第一个shell btw!

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <limits.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <dirent.h>e
#include <sys/types.h>
#include <sys/wait.h>    
#include <signal.h>
#include "sh.h"

int sh( int argc, char **argv, char **envp ){

    char *prompt = calloc(PROMPTMAX, sizeof(char));
    char *commandline = calloc(MAX_CANON, sizeof(char));
    char *command, *arg, *commandpath, *p, *pwd, *owd;
    char **args = calloc(MAXARGS, sizeof(char*));
    int uid, i, status, argsct, go = 1;
    struct passwd *password_entry;
    char *homedir;
    struct pathelement *pathlist;

    uid = getuid();
    password_entry = getpwuid(uid);
    homedir = password_entry->pw_dir; 

    if ( (pwd = getcwd(NULL, PATH_MAX+1)) == NULL ){
    perror("getcwd");
    exit(2);
    }

    owd = calloc(strlen(pwd) + 1, sizeof(char));
    memcpy(owd, pwd, strlen(pwd));
    prompt[0] = ' '; prompt[1] = '\0';

    pathlist = get_path();

    prompt = "[cwd]>";

    while ( go ){
    printf(prompt);

    commandline = fgets(commandline, 100, stdin);
    command = strtok(commandline, " ");

    printf(command);

    if (strcmp(command, "exit")==0){
        exit(0);
    }

    else if (strcmp(command, "which")==0){
    //  which();
    }

    else if (strcmp(command, "where")==0){
    //  where();
    }

    else if (strcmp(command, "cd")==0){
        chdir(argv[0]);
    }

    else if (strcmp(command, "pwd")==0){
        getcwd(pwd, PATH_MAX);
    }

    else if (strcmp(command, "list")==0){
        if (argc == 1){

        }

        else if (argc > 1){

        }
    }

    else if (strcmp(command, "pid")==0){
        getpid();
    }

    else if (strcmp(command, "kill")==0){

    }

    else if (strcmp(command, "prompt")==0){
        prompt = "argv[0] + prompt";
    }

    else if (strcmp(command, "printenv")==0){

    }

    else if (strcmp(command, "alias")==0){

    }

    else if (strcmp(command, "history")==0){

    }   

    else if (strcmp(command, "setenv")==0){

    }

    else{
        fprintf(stderr, "%s: Command not found.\n", args[0]);
    }



}
return 0;

} 
Run Code Online (Sandbox Code Playgroud)

大部分仍然是骨头,所以忍受我.

pax*_*blo 5

如果你改变:

printf(command);
Run Code Online (Sandbox Code Playgroud)

成:

printf("<<%s>>\n",command);
Run Code Online (Sandbox Code Playgroud)

你会明白为什么它永远不会匹配任何这些字符串.那是因为fgets没有剥离尾随换行符(a):

[cwd]>ls
<<ls
>>
Run Code Online (Sandbox Code Playgroud)

这意味着它将执行这行代码:

fprintf(stderr, "%s: Command not found.\n", args[0]);
Run Code Online (Sandbox Code Playgroud)

并且,因为你已经args[]用你的callocBANG 将所有这些值初始化为NULL !你的代码(尝试取消引用空指针是未定义的行为).

去看看这个答案,找到一个强大的用户输入解决方案,提示提示,缓冲区溢出保护,忽略太长线的剩余部分,最重要的是在这里,剥离换行符.


(a)另外,您不应该将用户输入printf作为格式字符串传递.猜猜如果我输入%s%s%s%s%s%s你的提示会发生什么:-)

而且,无关你的问题,ISO C的任务即sizeof(char)永远 1,这样你就不会需要你的语句分配使用它-我觉得它只是堵塞了不必要的代码.