简体   繁体   English

execv与Linux的任意命令配合使用-echo,date,ls等

[英]Use of execv with arbitrary commands of Linux — echo, date, ls, etc

I am trying to understand the execv() function. 我试图了解execv()函数。 Currently this is what I have. 目前这就是我所拥有的。

int mish_command_name(int argc, char *argv[])
{
    pid_t id;
    int status;

    id = fork();
    switch( id ) {

    case -1: // the fork() failed
        perror( "fork" );
        exit( EXIT_FAILURE );

    case 0: // we are the child process

        // if that failed, let's try /usr/bin
        execv( argv[0], argv );
        perror( "execv" );

        // use _exit() to avoid problems with the shared
        // stdout still being used by our parent
        _exit( EXIT_FAILURE );

        // will never reach this statement!
        break;

    default: // we are the parent
        break;

    }

    // parent will wait for child to exit
    id = wait( &status );
    if( id < 0 ) {
        perror( "wait" );
    } else {
        printf( "Parent: child %d terminated, status %d\n",
            id, status );
    }

    puts( "Parent is now exiting." );
    return 0;
}

Before I fork, I break the input up into tokens with this 在分叉之前,我用这个将输入分解为令牌

void forkProcess(char* buff)
{
    //printf("%s\n", buff );
    char *ptrArray[10];
    int   ptrIndex = 0;
    char *cp = buff;
    ptrArray[ptrIndex++] = cp; 
    while((cp=strchr(cp, ' ')))
    {
        *cp = '\0';
        ptrArray[ptrIndex++] = ++cp;
    } 
    ptrArray[ptrIndex+1] = NULL;

    mish_command_name(ptrIndex, ptrArray);
}

When I enter something like ' echo hello world ', I get this. 当我输入诸如“ echo hello world ”之类的内容时,我得到了。

mish[1]> echo hello
execv: No such file or directory
Parent: child 4511 terminated, status 256
Parent is now exiting.
mish[2]> echo hello world
execv: No such file or directory
Parent: child 4512 terminated, status 256
Parent is now exiting.

Some insight on how I'm messing this up here would be very helpful. 对我如何在这里弄乱一些见解将很有帮助。

This is simply because execv requires a full path name. 这仅仅是因为execv需要完整的路径名。 Try 尝试

/bin/echo foo

You can use execvp instead if you want to automatically search the PATH for your executable. 如果要自动搜索可执行文件的PATH,则可以改用execvp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM