使用c语言为shell程序创建历史命令

标签 c shell minix

我想做的是在我的 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(用户输入的sets 命令)放入**cmdsHistory 数组中的问题。

有什么帮助吗?

最佳答案

一个修复方法是改变

char **cmdsHistory;

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

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

修复泄漏就像

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

确保在启动时将所有指针初始化为 NULL

关于使用c语言为shell程序创建历史命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22063312/

相关文章:

c - C 中的面向对象程序 - 列表

c - 传递一个 int 指针,然后检查值或 null

c - ASM/C 中的中断处理程序 - 如何? -Minix

c - 使用函数在c中填充并返回字符串数组

python - 在启动 python shell 时自动执行命令

linux - 我如何从 awk 中的字符串中选择第 s 个值?

java - IntelliJ 无法识别 PATH 变量

linux - 将 JVM 移植到 MINIX

c - Minix 3 stdio.h 无法识别文件 *f

c - x11 中的叠加窗口不断闪烁