簡體   English   中英

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

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

我試圖了解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.

對我如何在這里弄亂一些見解將很有幫助。

這僅僅是因為execv需要完整的路徑名。 嘗試

/bin/echo foo

如果要自動搜索可執行文件的PATH,則可以改用execvp

暫無
暫無

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

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