在尝试创建一个非常基本的命令行解释器时,我遇到了一个我似乎无法弄清楚的部分。当我检查所需分隔符的令牌时,我似乎无法正确启用 && 和 || 功能。下面列出的是插入 args 然后创建进程的循环。
我现在只关注 && 并计划使用该实现来帮助 || 功能。你们可以看看并帮助我指出正确的方向吗?
旁注:这也是我第一次用 C 编写程序,因此代码中可能会出现一些错误。
这是一个家庭作业问题。
谢谢
更新了我到目前为止的完整程序代码。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#define ARG_SIZE 1<<16
#define MAXLINE 100
char *args[ARG_SIZE];
int place = 0;
int return_status;
void insert( char *token ){
args[ place ] = token;
place++;
}
void create() {
size_t nargs = place;
pid_t pid;
if ( nargs == 0 ) return;
if ( !strcmp( args[0], "exit" ) ) exit(0);
pid = fork();
if ( pid ) {
pid = wait( return_status );
} else {
if ( access( args[ 0 ], X_OK ) ){
if( execvp( args[ 0 ], args ) ) {
puts( strerror( errno ) );
exit( 127 );
}
}else{
puts( strerror( errno ) );
exit( 127 );
}
}
int i = 0;
for ( i ; i < place + 1; i++)
args[ i ] = NULL;
place = 0;
}
int main( int argc, char *argv[] ){
char line[MAXLINE+1]; /* an input line */
int c; /* a single input char or EOF */
int n; /* line length */
char *token; /* pointer to an input token */
for(;;) { /* repeat until end of file */
write( 1, "#>", 2 );
if (fgets(line,MAXLINE,stdin) == NULL) /* end of file? */
exit(0);
n = strlen(line); /* get length of line */
if (n == 0) /* if line is empty */
continue;
if (line[n-1] != '\n') { /* does input end with '\n' ? */
fprintf(stderr,"Line too long.\n"); /* no, so line is too long. */
/*--------------------------------------------*/
/* Read and ignore input through end of line. */
/*--------------------------------------------*/
while ((c = fgetc(stdin)) != '\n') {
if (c == EOF) {
fprintf(stderr,"Unexpected end of file\n");
exit(1);
}
}
continue;
}
write( 1, line, strlen( line ) );
line[n-1] = '\0'; /* remove the end of line */
/*-------------------------------------------------------------*/
/* Identify and process each token (i.e. sequence of non-blank */
/* characters delimited by whitespace). For "ordinary" tokens */
/* (i.e. "words") we just display them. For the ||, &&, and ; */
/* items we display them with a textual explanation. */
/*-------------------------------------------------------------*/
token = strtok(line," \t");
while (token != NULL ) {
insert( token );
if (!strcmp(token,"&&")){
place--;
args[ place ] = NULL;
create();
if( return_status == -1)
write( 1, "Wait failed.\n", 12 );
if( return_status & 0xff ){
int i = 0;
for( i; i < place; i++)
args[ i ] = NULL;
place = 0;
while( strcmp( token, "||" ) || strcmp( token, ";" ) ) ;
}
}
else if (!strcmp(token,"||")){
place--;
args[ place ] = NULL;
completed = 0;
create();
}
else if (!strcmp(token,";")){
place--;
args[ place ] = NULL;
create();
}
else{
}
token = strtok(NULL," \t");
}
create();
}
return 0;
}