关于Linux上 execve的argv的参数问题

发布时间 2023-03-28 21:56:24作者: DreamOfSJ

关于Linux上 execve函数的参数argv的问题

​ 今天学习了CSAPP的第8章异常控制流。在写shell时,调用了execve函数,出现了无法执行程序的问题.

先贴上代码:

extern char ** __environ;

void unix_error(char *msg) /* unix-style error */
{
    fprintf(stderr, "%s: %s\n", msg, strerror(errno));
    exit(0);
}

pid_t Fork(void)
{
    pid_t pid;

    if ((pid = fork()) < 0)
        unix_error("Fork error");
    return pid;
}

int main() {

    pid_t pid;
    char * myargv[] = {"/home/a/Desktop/Mydocument/Shell Lab/MyCode/hello"};


    if( (pid = Fork()) == 0 ) {
        int c;
        if((c =execve(myargv[0], myargv, __environ)) < 0) {
            unix_error("ERROR");
        }
    }else {
        sleep(10);
    }



    return 0;


}

这是hello的源代码:

#include<stdio.h>
int main() {
    printf("Hello, World");

    return 0;
}

执行后:

出现了Bad address的问题

在查阅了书之后,有这么一张图:

​ 在argv句段数组的最后一个单元是NULL,换句话说,argv数组以执行文件的文件地址为开始,以NULL结束
​ 于是修改代码为:

int main() {

    pid_t pid;
    // 在myargv中加入NULL
    char * myargv[] = {"/home/a/Desktop/Mydocument/Shell Lab/MyCode/hello", NULL};
   
    if( (pid = Fork()) == 0 ) {
        int c;
        if((c =execve(myargv[0], myargv, __environ)) < 0) {
            unix_error("ERROR");
        }
    }else {
        sleep(10);
    }



    return 0;


}

在myargv中加入NULL

运行结果:

成功!!!!

记录一下卡我一天的Bug。