gpt4 book ai didi

linux - UNIX Shell 和历史特征

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:19 25 4
gpt4 key购买 nike

如何在 unix shell 中添加历史功能以允许用户访问最近输入的命令,用户将能够访问最多 10 个命令,方法是使用特征。

此评论解释了项目的历史部分:

用户最多可以使用 10 个命令特征。命令将从 1 开始连续编号,并且编号将继续超过 10。例如,如果用户输入了 35命令,最近的 10 个命令将编号为 26 到 35。用户将能够通过输入命令列出命令历史记录历史在 osh> 提示符下。例如,假设历史包括命令(从最近到最近):ps, ls -l, top, cal, who, 日期命令历史将输出:6 秒5 升 -升4顶3卡2 谁1个日期你的程序应该支持两种检索命令的技术从命令历史:1.当用户输入!!时,历史上最近的命令是执行。2.当用户输入单!后跟一个整数N,第N执行历史中的命令。

这是我的代码,包括历史部分,但我有错误并且不知道如何修复它。请帮忙

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MAX_LINE 80

char *history[10][MAX_LINE];
int po;




void setup(char inputBuffer[], char *args[],int *background)
{
int length,
i,
start,
ct;

ct = 0;

length = read(STDIN_FILENO, inputBuffer, MAX_LINE);

start = -1;
if (length == 0)
exit(0);
if (length < 0){
perror("error ");
exit(-1);
}


for (i = 0; i < length; i++) {
switch (inputBuffer[i]){
case ' ':
case '\t' :
if(start != -1){
args[ct] = &inputBuffer[start];
ct++;
}
inputBuffer[i] = '\0';
start = -1;
break;

case '\n':
if (start != -1){
args[ct] = &inputBuffer[start];
ct++;
}
inputBuffer[i] = '\0';
args[ct] = NULL;
break;

case '&':
*background = 1;
inputBuffer[i] = '\0';
break;

default :
if (start == -1)
start = i;
}
}
args[ct] = NULL;
}



int main(void)
{
char inputBuffer[MAX_LINE];
int background;
char *args[MAX_LINE/2+1];

while (1){
background = 0;
printf("os>");
fflush(0);
setup(inputBuffer, args, &background);

/**
* After reading user input, the steps are:
* (1) fork a child process using fork()
* (2) the child process will invoke execvp()
* (3) if command included &, parent will invoke wait()
*/

pid_t pid = fork();
printf("Fork created.\n");
/*
For example, if the
user enters the command ps -ael at the osh> prompt, the values stored in the
args array are:
args[0] = "ps"
args[1] = "-ael"
args[2] = NULL
This args array will be passed to the execvp() function, which has the
following prototype:
execvp(char *command, char *params[]);
*/

if(pid < 0){
printf("Fork failed.\n");
}else if(pid == 0){
if( strcmp(args[0],"history") == 0){ /* Print History */
displayHistory();
}else if(strcmp(args[0],"r") == 0){ /* r num */
int index = (int) args[1];
/*runHistoryAt( index - 1);*/
}else if(strcmp(args[0],"rr") == 0){ /* Run recent */
/*runHistoryAt(0);*/
}else{ /* Execute normally */
printf("executing..., adding to history buffer\n");
/* Add args to history buffer */
int j;
for (j = 0; j < sizeof(args); j++) {
history[po][j] = args[j];
}
po = (po + 1) % 10;
/* Execute! */
execvp(args[0],args);
}
}

if(background == 0){
wait(NULL);
}else{
setup(inputBuffer, args, &background);
}
}
}

最佳答案

我会使用 GNU readline图书馆。它为您提供行版和 history支持,你也可以完成。

关于linux - UNIX Shell 和历史特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27719289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com