[英]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.