c - 这个基本的 shell 程序有什么问题?前几个命令运行良好,但结果总是以段错误结束

标签 c linux shell lex

我必须使用 lex 和 c 代码构建一个简单的 shell 程序。 lex 部分用于分解输入。它已为我提供,预计我不会更改它。我正在让我的代码运行像“ls”这样的基本命令。它似乎在我运行命令的前几次有效,但最终总是出现段错误。这是提供的 lex 代码:

%{
int _numargs = 10;
char *_args[10];
int _argcount = 0;
%}

WORD [a-zA-Z0-9\/\.-]+
SPECIAL [()><|&;*]

%%
_argcount=0; 
_args[0]=NULL; 

{WORD}|{SPECIAL} { 
if(_argcount < _numargs-1) {
_args[_argcount++]= (char *)strdup(yytext);
_args[_argcount]= NULL;
}
}

\n return (int)_args;

[ \t]+

.

%%

char **getln() {
return (char **)yylex();
}

这是 C 代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>

extern char **getln();

int main() {
    int i;
    char **args; 
    int child1;
    int status1;
    int counter=0;
    int argCount = 1;

    char **array = (char **)malloc(1500 * sizeof(char *));
    for (i = 0; i < 1500; ++i) {
        array[i] = (char *)malloc(500);
    }
    strcpy(array[0],"ls\0");
    array[1] = NULL;

    while(1) {
        args = getln();
        printf("is error here?");
        strcpy(array[0], args[counter]);

        for(i = (counter+1); args[i] != NULL; i++) {
            printf("\nRight before copying to subarray");
            strcpy(array[argCount], args[i]);
            argCount++;
        }

        array[argCount] = NULL;

        if (strcmp(args[counter],"exit")==0) exit(0);

        child1 = fork();
        if(child1==0){

            execvp(array[0], array);
            printf("Unknown command, please try again.");
            exit(1);
        }
        else{
            while (wait(&status1) != child1);
        }

        for(i = 0; args[i] != NULL; i++) {
            printf("Argument %d: %s\n argCount: %d", i, args[i], argCount);
        }
        argCount = 1;
        counter++;
    }
} 

提前感谢您的任何建议。如果有一些简单的方法来调整 getln() 函数以在每次调用它时覆盖 args 数组,这可能比我正在尝试的更容易,但我不知道如何去做。

最佳答案

你好像放了

_argcount=0;
_args[0]=NULL;

在规则部分的顶部,希望这些语句将在 yylex() 的开头执行。你注意到它们没有被执行(它一直附加到以前的值,因为 _argcount 永远不会回到 0)。

显而易见的做法是将这些语句移到 yylex() 之前的 getln() 中。

您现在拥有的是一个词法分析器,它会忽略输入中的字符串 _argcount=0;,因为它会匹配该模式,并且不会执行任何操作。第二行更酷,因为 [0] 是一个字符类。它使词法分析器忽略字符串 _args0=NULL;

关于c - 这个基本的 shell 程序有什么问题?前几个命令运行良好,但结果总是以段错误结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21391425/

相关文章:

c - 将结构数组转换为二叉搜索树

c - 为什么相同显卡但不同机器上的 opencl 代码存在基准差异?

c - 正弦函数频率突然跳变

c - 为什么 pclose(3) 不等待 shell 命令终止

bash - 编写一个 shell 脚本,在 1 行中查找并输出文件名和内容

c - 字符串数组正确扫描,然后一起运行

linux - 我可以使用 openJDK 而不是 Oracle JDK 安装 RubyMine 5 吗?

c++ - 带有 SCHED_OTHER 的可移植 pthread_setschedparam

linux - 允许在文件超过一定大小时清空文件的 shell 脚本

linux - 将大括号扩展与过程替换相结合