【问题标题】:Getting an unexpected seg fault when creating a custom shell prompt创建自定义 shell 提示时出现意外的段错误
【发布时间】:2021-07-20 00:23:22
【问题描述】:

所以下面的 sn-p 应该在一个简单的 shell 程序 'my257sh'> 中进行提示,或者如果在启动时将 -p 用作命令行 arg,然后是一个字符串用作自定义提示。

自定义提示运行良好,但在没有附加参数的情况下启动时出现段错误。

谁能告诉我我做错了什么难以置信的简单和愚蠢的事情?

int main(int argc, char *argv[]) {
    char cmdline[MAXLINE]; /* Command line */
    char def_prompt[20] = "my257sh";
    const char prompt_check[2] = "-p";
    char new_prompt[20];

    if (argc > 0){
        if (strstr(argv[1], prompt_check)) {
            strcpy(new_prompt, argv[2]);
        }
    }
    else {
        strcpy(new_prompt, def_prompt);
    }

    signal(SIGINT, sigIntHandler); // ignores ctrl + C interrupt

    while (1) {
    /* Read */
        printf("%s> ",new_prompt);
        ...

【问题讨论】:

  • const char prompt_check[2] = "-p"; -> const char prompt_check[3] = "-p";

标签: c shell segmentation-fault prompt


【解决方案1】:

argc 总是 > 0 : argv[0] 包含程序的名称。 检查

If argc > 1

同样在 -p 的情况下检查

If argc > 2

您还需要检查提示的长度以避免复制太小的字符串

【讨论】:

    【解决方案2】:

    argc 包含在 shell 上传递的参数数量,包括命令本身,所以argc 将始终为> 0,因为如果没有给出参数,它至少为1。

    如果您不传递任何参数,则argv[1] 将包含NULL指针。如果你只传递一个参数,那么argv[2] 就是一个NULL 指针。

    if (argc > 2)
    {
        if (strstr(argv[1], prompt_check))
            strcpy(new_prompt, argv[2]);
    }
    else
    {
        strcpy(new_prompt, def_prompt);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      相关资源
      最近更新 更多