簡體   English   中英

簡單的Linux Shell-execvp()失敗

[英]Simple Linux Shell - execvp() failing

我需要一個用於類的簡單shell的幫助,而且我擔心我不太了解execvp()函數的工作方式。

Shell並沒有做很多事情,不支持管道,重定向,腳本或類似的東西。 它僅讀取命令,讀取選項(命令為option [0]),然后派生。

它工作了幾次,然后開始給我有關無法找到命令的錯誤。 此處發布的其他類似問題與管道或重定向有關。

請原諒noobcode,它雖然不漂亮,但我希望它清晰易讀:

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

#define OPT_AMT 10

const size_t SIZE = 256;
int i = 0;
int o = 0;

int main(void) {

    // initializing data

    int exit = 0;
    char cwd[SIZE];
    char cmd[SIZE];
    char input[SIZE * OPT_AMT];
    char *opt[OPT_AMT];
    getcwd(cwd, SIZE);

    // main loop

    while (exit == 0) {
        // reset everything
        o = 1;
        i = 0;
        cmd[0] = "\0";
        while (i < OPT_AMT) {
            opt[i++] = "\0";
        }

        // get input
        printf("%s $ ", cwd);
        scanf("%s", cmd);
        gets(input);
        opt[0] = cmd;

        char *t = strtok(input, " ");
        while (t != NULL) {
            opt[o++] = t;
            t = strtok(NULL, " ");
        }

        // if exit, exit
        if (strcmp(cmd, "exit") == 0) {
            exit = 1;
        }
        // else fork and execute
        else {
            pid_t pID = fork();

            if (pID == 0) { // child process
                execvp(cmd, opt);
            } else if (pID < 0) { // failed to fork
                printf("\nFailed to fork\n");
            } else { // parent process
                wait(0);
            }
        }
    }

    // cleanup

    printf("\nFinished!  Exiting...\n");
    return 0;
}

有什么公然的錯誤嗎? 我最近添加了退出條件和重置options數組。

另外,這是我的第一個問題,因此請提醒我可能違反的任何規則。

對於初學者,這

cmd[0] = "\0";

必定是

cmd[0] = '\0';

聽您的編譯器的警告。

要啟用它們,請使用-Wall -Wextra -pedantic選項(對於gcc)。


另外,您可能最好將opt的元素初始化為指向“ nothing”,即NULL但指向文字"\\0"

    while (i < OPT_AMT) {
        opt[i++] = NULL;
    }

因為execvp()要求optNULL終止的C-“字符串”數組(感謝Paul提及/措辭相關背景)。


另外^ 2:不要使用gets() ,因為它很邪惡,甚至不再是C標准的一部分。 代替

gets(input);

采用

fgets(input, sizeof input, stdin);

gets()容易讓用戶使傳遞的(輸入)緩沖區溢出。 (想到這一點,我沒有保羅,順便說一句; ;-))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM