Execve()添加了两个额外的参数

当我编译以下代码并在其上运行strace时,我可以看到它向args[]数组添加了两个附加元素。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc,char **argv)
{
    char *args[2];
    args[0] = "/bin/ls";
    args[1] = "-lh";
    execve(args[0],args,NULL);

    return 1;
}

strace说,这实际上是所谓的:

execve("/bin/ls",["/bin/ls","-lh","\340\301\361\267","\1"],NULL)

iCMS 回答:Execve()添加了两个额外的参数

您需要向参数数组的最后一个元素添加一个null ptr。否则execve不知道您的数组在哪里结束。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc,char **argv)
{
    char *args[3];
    args[0] = "/bin/ls";
    args[1] = "-lh";
    args[2] = NULL;
    execve(args[0],args,NULL);

    return 1;
}

因此,基本上,您所看到的是execv传递随机参数,直到它在您指向数组的内存中找到NULL为止。当然,它也可能崩溃。

本文链接:https://www.f2er.com/1791675.html

大家都在问