0

C で非常に基本的なシェル プログラムを作成しようとしています。直面している問題は、文字ポインターの argv 配列を入力から取得した単語で埋めようとすることです。以下の parse() 関数を使用して argv 配列の内容を埋めようとした後、その内容を出力しようとすると、セグメンテーション違反が発生します。これはおそらく、範囲外の argv 配列の一部にアクセスしようとしていることを意味します。ただし、配列を埋める引数を 1 つだけ指定した場合でも、segfault が発生します。argc を出力するために使用される printf 呼び出しは、入力に基づいて argc の正しい値を返しますが、*argv[0] を指定した 2 番目の printf 呼び出しが segfault の原因となっています。エラーが argv の内容を印刷しようとしている方法にあるのか、それとも argv を間違って入力しようとしているためにエラーが発生したのか疑問に思っています。

編集: getword() 関数がテキスト行を受け取り、スペースで区切られた最初の単語とその他の区切り文字を返すことを追加する必要があります。必要に応じて、単語を分割するすべての区切り記号を投稿できますが、問題は getword() によるものではないと思います。

編集 2: ヘッダー ファイルに追加され、メインに #include ステートメントが含まれています。

編集 3: main() の下に getword 関数を追加し、p2.h の下に getword.h を追加しました

main に含まれるヘッダー ファイル p2.h は次のとおりです。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "getword.h"
#include <signal.h>

#define MAXITEM 100

getword.h:

#include <stdio.h>
#include <string.h>
#include <strings.h>

#define STORAGE 255

int getword(char *w);

int parse(char *, char *[]);

主な機能は次のとおりです。

#include "p2.h"
int main() {
    pid_t pid, child_pid;
    int argc, inputRedirect;
    char *devNull;
    devNull = (char *) malloc(10);
    strcpy(devNull, "/dev/null");
    char *argv[MAXITEM];
    char commandLine[STORAGE];


    for (;;) {
        printf("p2: ");
        scanf("%s", commandLine);
        argc = parse(commandLine, argv);
        printf("argc = %d\n", argc);

        if(argc == 0)
            continue;
        printf("*argv = %s\n", *argv[0]);
        child_pid = fork();
        if (child_pid < 0) {
            printf("Cannot fork! Terminating...");
            exit(1);
        } else if (child_pid == 0) {
            inputRedirect = open(devNull, O_RDONLY);
            dup2(inputRedirect, STDIN_FILENO);
            close(inputRedirect);
            execvp(*argv, argv);
        }
        else {
            for(;;) {
                pid = wait(NULL);
                if(pid == child_pid)
                   break;
            }
            printf("Child's pid is %d\n", child_pid);
        }
    }
    killpg(getpid(), SIGTERM);
    printf("p2 Terminated.\n");
    exit(0);
}

int parse(char *commandLine, char *argv[]) {
    int i, argc = 0;
    char *commandPointer = commandLine;
    while (*commandPointer != '\0') {
        *argv = commandPointer;
        argc++;
        getword(commandPointer);
    }
    *commandPointer = '\0';
    *argv = '\0';
    return argc;
}

getword.c:

#include "getword.h"
#include <stdlib.h>

/*Function Prototypes*/
int tilde(char *p, int i);
int BSFollowedByMetaCharacter(int c, char *w);


int getword(char *w) {

    int c;
    int index = 0;

    /*This while loop removes all leading blanks and whitespace characters
     * The if statement then tests if the first character is a new line or
     *  semicolon metacharacter*/
    while ((c = getchar()) == ' ' || c == '\t' || c == '\n' || c == ';') {
        if (c == '\n' || c == ';') {
            w[index] = '\0';
            return 0;
        }
    }

    /*This if statement calls ungetc() to push whatever character was taken
     * from the input stream in the previous while loop back to the input
     * stream. If EOF was taken from the input stream, ungetc() will return EOF,
     * which will then cause getword() to return -1, signalling that it reached
     * the End Of File. */
    if (ungetc(c, stdin) == EOF)
        return -1;

    /*This if statement deals with some of the "non-special" metacharacters.
     * If one of these metacharacters is pulled from the input stream by getchar(),
     * it is stored in w and null-terminated. getword() then returns the length of
     * the current string stored in w. If getchar() pulls anything besides one of the
     * specified metacharacters from the input stream, it is then returned using ungetc() after
     * the if statement.*/
    if ((c = getchar()) == '<' || c == '>' || c == '|' || c == '&') {
        w[index++] = c;
        int d = getchar();
        if (c == '>' && d == '>')
            w[index++] = d;
        else {
            ungetc(d, stdin);
        }
        w[index] = '\0';
        return index;
    }
    ungetc(c, stdin);

    /*This while statement handles plain text from the input stream, as well as a few 'special'
     * metacharacters. It also ensures that the word scanned is shorter than STORAGE-1 bytes.*/
    while ((c = getchar()) != ' ' && c != '<' && c != '>' && c != '|'
        && c != ';' && c != '&' && c != '\t' && c != '\n' && c != '\0'
        && index <= STORAGE - 1) {
        if (c == '~') {
            int *ip = &index;
            index = tilde(&w[index], *ip);
            continue;
        }/*END IF*/
        else if (c == '\\') {
            int d = c;
            c = getchar();
            if (BSFollowedByMetaCharacter(c, w)) {
                w[index++] = c;
                continue;
            } else {
                w[index++] = d;
            }

        }/*END ELSE IF*/
        w[index] = c;
        index++;
    }/*END WHILE*/

    ungetc(c, stdin);/*This final ungetc() call is used to push any meta characters*/
    w[index] = '\0'; /*used as delimiters back to the input stream, to be retrieved*/
    return index;    /*at the next call of getword().                                      */
}/*END getword()*/

int tilde(char *cp, int i) {
    int *ip;
    ip = &i;
    char *p = cp;
    char *o;
    o = (strcpy(p, getenv("HOME")));
    int offset = strlen(o);
    *ip = *ip + offset;
    return i;
}

int BSFollowedByMetaCharacter(int c, char *w) {
    if (c == '~' || c == '<' || c == '>' || c == '|' || c == ';' || c == '&'
        || c == ' ' || c == '\t' || c == '\\') {
        return 1;
    } else {
        return 0;
    }
}
4

1 に答える 1

0

の関数はgetword.c正しいようです。あなたの問題は機能にありますparse

を使用するにはexecvp、 の内容は次のようにargvする必要があります (input:"hello world"):

argv[0] -> "hello"
argv[1] -> "world"
argv[2] -> NULL

ここに、argv文字ポインタの配列があります。ただし、関数では、ここでは単純な文字ポインターのようparseに扱っています。argv

*argv = commandPointer;

そしてここ:

*argv = '\0';

parse 関数を次のように変更します。

int parse(char *commandLine, char *argv[]) {
    int argc = 0;
    char *commandPointer;
    argv[argc++] = commandLine;

    do{
        commandPointer = (char*)malloc(sizeof(char) * STORAGE);
        argv[argc++] = commandPointer;
        getword(commandPointer);
    }while(*commandPointer != '\0');
    argv[argc] = NULL;
    return argc;
}

if-elseここで、次のようにツリーの後に割り当てられたメモリを解放する必要があります。

for(int i = 0; i < argc; i++) free(argv[i]);
于 2013-11-25T11:30:42.537 に答える