【问题标题】:Creating a history command for a shell program using the c language使用c语言为shell程序创建历史命令
【发布时间】:2014-02-27 08:47:57
【问题描述】:

我想做的是在我的 shell 程序中开发一个历史命令。因此,每当用户写入历史记录时,最后输入的 10 个命令都会显示在屏幕上

这是我的一段代码..

  int i;
  char cmd[4096];
  int cmdHisC =0; 
  char *cmdHistory;
  char *cmdsHistory[10];


      while(1) {
    /*** Read input from shell ***/
        fgets(cmd,4096,stdin);
if(strcmp(cmd,"") != 0)
{
    if((cmdHistory= strdup(cmd)) != NULL)
    {
        if (cmdsHistory[cmdHisC] != NULL) 
        free(cmdsHistory[cmdHisC]);

        cmdsHistory[cmdHisC] = cmdHistory;
        cmdHisC++;
    }       
    else
    fprintf(stderr, "Error, Cannot save this command in the history pointer: Out of memory\n");

    if(cmdHisC>9)
        cmdHisC=0;
}

要打印历史,我的意思是 cmdsHistory,代码如下:

 if(strcmp(argsCmd[0], "history")==0)
    {
       for(int n = 0; n<10 ; n++) 
        {
        if(cmdsHistory[n] != NULL)
        printf("History command  %d: %s\n", n, cmdsHistory[n]);
        }
    }

然后每当用户写入历史记录时,我都会遍历 cmdsHistory 并打印结果。

我无法将 *cmdHistory(用户输入的设置命令)放入 **cmdsHistory 数组的问题。

有什么帮助吗?

【问题讨论】:

  • 历史代码看起来很完美,这部分代码可能有问题

标签: c shell minix


【解决方案1】:

一个修复会改变

char **cmdsHistory;

char *cmdsHistory[10]; //or any desire number/macro

但您的程序仍然会泄漏内存,方法是在一个循环后调用strdup 并重置i as 0。请修复它。

修复泄漏就像

if (cmdsHistory[cmdHisC]) {
    free(cmdsHistory[cmdHisC]);
    cmdsHistory[cmdHisC] = cmdHistory;
}

确保在启动时初始化所有指向 NULL 的指针。

【讨论】:

  • 用于在开始时将所有指针初始化为 NULL。我应该这样做吗?字符 *cmdsHistory[10]=NULL; char *cmdHistory=NULL;
  • 只需使用 for 循环即可。 for (i=0;i&lt;10;i++) cmdsHistory[i] = NULL;
  • 您好,我发现我还有另一个问题。每当我超过 10 个条目时,然后键入 history 作为命令。我会收到很多奇怪的数字,然后是一条消息错误内存(核心转储)!关于这个错误的任何想法
猜你喜欢
  • 2015-12-30
  • 2013-12-25
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
  • 1970-01-01
相关资源
最近更新 更多