简体   繁体   中英

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

I am trying to understand the execv() function. 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.

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. Try

/bin/echo foo

You can use execvp instead if you want to automatically search the PATH for your executable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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