首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解‘`execv`’在‘`execv`’失败时工作的原因

理解‘`execv`’在‘`execv`’失败时工作的原因
EN

Stack Overflow用户
提问于 2018-12-17 14:13:09
回答 1查看 1.4K关注 0票数 0

我被要求在C中实现一个‘mini’,我决定使用execv,但它没有工作,当我将它更改为execvp工作时!查看代码(动作在tokExec函数中)

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>


void tokExec(char command[128])
{
    // 'strtok' may look innocent, but it modifies the string, so I want a copy of the original command.
    char tokString[128];
    // 'strlen' is the lenghth without the null terminator.
    strncpy(tokString,command,strlen(command)+1);


    char* tokPtr = NULL;
    char tok[] = " ";
    int narg = 0;
    tokPtr = strtok(tokString,tok);
    char *myargs[64];

    while(tokPtr != NULL)
    {
            printf("arg %d is: %s\n",narg,tokPtr);
            myargs[narg] = tokPtr;
            narg = narg + 1;
            tokPtr = strtok(NULL,tok);
    }
    printf("Total number of arguments: %d\n",narg);

    // add the final 'NULL' element.
    myargs[narg] = NULL;

    execvp(myargs[0],myargs);
    printf("error\n");
    exit(1);
}

void normal()
{
    char command[128];
    strcpy(command,"default\0");
    printf("myShellZ > ");
    gets(command);
    while(strcmp(command,"exit") != 0)
    {
            int status;
            pid_t pid;
            if( (pid = fork()) == 0 )
            {
                    tokExec(command);
            }
            wait(&status);
            printf("myShellz > ");
            gets(command);
    }
}

void debug()
{
    // TO DO ....
    int a = 3;
}

// switching between shell modes: normal or debug.
int main(int argc, char* argv[])
{
    if(argc == 1)
            normal();
    else if(strcmp("-debug",argv[1]))
            debug();
    else
            exit(1);

    exit(0);
}

如果我将使用execvp代替tokExec末尾的execv,如果我的输入仅为lsps等,那么很好,但是如果我向输入中添加参数,例如:ls -l myshell.c或evev --只是ls -lps aux --我得到了一个error输出。

man几乎没有提到这些函数之间的区别,但它声称:

execv()、execvp()和execvpe()函数提供了指向以空结尾的字符串的指针数组,这些字符串表示新程序可用的参数列表。根据约定,第一个参数应该指向与正在执行的文件相关联的文件名。指针数组必须以空指针结束。

总之,在这种情况下修复我的程序的execvexecvp有什么区别?我知道execv也适用于bash命令,因为如果我输入bash命令时没有参数,它就能工作,而这两个函数的签名是相同的。谢谢你的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-17 14:24:24

答案在手册页。如果你读了你引用的那部分之后的那一节,它就会谈到不同之处。

如果指定的文件名不包含斜杠(/)字符,execlp()、execvp()和execvpe()函数将重复shell在搜索可执行文件时的操作。该文件在路径环境变量中指定的以冒号分隔的目录路径名列表中查找。如果未定义此变量,路径列表默认为当前目录,后面跟着由confstr(_CS_PATH)返回的目录列表。(这个confstr(3)调用通常返回值“/bin:/usr/bin”)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53817023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档