[英]UNIX Shell and History Feature
如何在UNIX shell中添加历史记录功能以允许用户访问最近输入的命令,用户将可以使用该功能访问多达10个命令。
此注释解释了该项目的历史部分:
使用该功能,用户最多可以访问10个命令。 这些命令将从1开始连续编号,并且编号将继续超过10。例如,如果用户输入了35个命令,则最近的10个命令将编号为26到35。用户将能够列出命令历史记录通过在osh>提示符下输入命令历史记录。 例如,假设历史记录由命令组成(从最新到最近):ps,ls -l,top,cal,who,date该命令历史记录将输出:6 ps 5 ls -l 4 top 3 cal 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.