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

时间:2014-05-11 17:23:40

标签: c linux

我想了解execv()函数。目前这就是我所拥有的。

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;
}

在我分叉之前,我使用此

将输入分解为令牌
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);
}

当我输入“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.

我对如何弄乱这一点的一些见解会非常有帮助。

1 个答案:

答案 0 :(得分:3)

这只是因为execv需要一个完整的路径名。试试

/bin/echo foo

如果您想自动在PATH中搜索可执行文件,可以使用execvp