繁体   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