簡體   English   中英

嘗試使用 execvp 在 C 中執行外部命令(在類似 shell 的程序中)

[英]Trying to use execvp to execute external commands in C (in a shell like program)

所以我必須實現對執行外部命令的支持(對於 C 編程語言中的 linux)。 這就是我到目前為止所擁有的,我使用了 readline 庫作為歷史函數,但這無關緊要......有人能告訴我我做錯了什么嗎? (我認為這是我稱之為“execvp”的方式)所以這是我的代碼:

#include<fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> 
#include <readline/readline.h>
#include <readline/history.h>
#define BUFFER_SIZE 256
#define READFILE_SIZE 4096

char ** parseCMD( char * );
void  EXEC(char *, char *);

int main(int argc, char ** argv)
{
    char  myPrompt[]= {'>', '_', '\0'};
    char *currLine = (char* ) malloc(sizeof(char) * BUFFER_SIZE),
                 *command = (char* ) malloc(sizeof(char) * BUFFER_SIZE),
                            *argument = (char* ) malloc(sizeof(char) * BUFFER_SIZE);

    currLine = readline(myPrompt);
    while((strcmp(currLine, "exit") != 0))
    {
        command = strtok(currLine, " ");
        argument = strtok( NULL, "");
        EXEC(command, argument);
        currLine = readline(myPrompt);
    }
return 0;
}

char ** parseCMD( char * buff )
{
    int i = 0, n = strlen(buff), j, count = 0;
    char ** CMDargs = (char **) malloc( sizeof( char ) * 100 * 100);
    if( buff == NULL )
        return NULL;
    for(i; i < n; i ++)
    {
        j = 0;
        char * aux = (char *) malloc( sizeof( char ) * 100);
        while( buff[i] != ' ' || buff[i] != '\t' || buff[i] != '\n')
        aux[j++] = buff[i++];
        aux[j] = '\0';
        CMDargs[count] = strdup( aux );
        count++;
        //printf("Argument %d is: %s", count - 1, CMDargs[count - 1]);
        free(aux);
    }
CMDargs[ count ] = NULL;
return CMDargs;
}

void  EXEC(char *command, char *argBuffer)
{
    pid_t  pid;
    int status, fd[2], n;
    char s[255];
    char ** Args;
    pipe( fd );
    Args = parseCMD( argBuffer );
    if ((pid = fork()) < 0)
    {
        printf("ERROR: forking child process failed\n");
        exit(1);
    }
    else if (pid == 0)
    {
        close(fd[0]);
        dup2(fd[1],1);
        if (execvp(command, Args) < 0)
        {
            printf("ERROR: execvp call failed\n");
            exit(1);
        }
        close(fd[1]);
    }
    else
    {
        close(fd[1]);
        while( ( n = read( fd[0], s, 255 ) ) > 0 )
        {
            s[n] = '\0';
            printf("%s",s);

        }
        while (wait(&status) != pid);
        close(fd[0]);
    }
}

這個bug太多了,問問你自己,當我輸入空命令時會發生什么(變量命令為NULL,稍后你會得到段錯誤),如果我輸入不帶參數的命令會發生什么(變量參數為NULL,你稍后會出現段錯誤),如果我輸入帶參數的命令會發生什么? (而 parseCMD 函數中的循環永遠不會終止,最終您將訪問您不應該訪問的內容)。 也許是時候學習使用調試器了。 嘗試逐行執行程序並觀察發生了什么。

暫無
暫無

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

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