gpt4 book ai didi

c - 如何在 environ 中使用 execvp/execlp

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:09 24 4
gpt4 key购买 nike

如何在 execlp 之前设置环境?

     #include <stdio.h>
#include <unistd.h>
#include <syslog.h>
// Tried extern char **environ;

int main (int argc, char *argv[])
{
// Tried environ = -- gives compile error
char** environ =
{
"foo=bar",
"hello=world",
0 // zero byte
};

//environ = ??
execlp("env", "env", (char*)0);
return 0;
}

没有打印 foo = bar谢谢。

最佳答案

man execlpman environ将帮助:

The execle() and execvpe() functions allow the caller to specify the environment of the executed program via the argument envp. The envp argument is an array of pointers to null-terminated strings and must be terminated by a NULL pointer. The other functions take the environment for the new process image from the external variable environ in the calling process.

environunistd.h 中声明作为extern ,您需要在调用 execlp() 之前填充变量.另请注意 environ 中的字符串预计格式为 key=value ;

#include <stdio.h>
#include <unistd.h>

// declare environ as extern
extern char** environ;

int main (int argc, char *argv[])
{

// populate environ
environ[0] = "foo=bar";
environ[1] = NULL;

// call execlp
execlp("/usr/bin/env", "", (char *)0);

return 0;
}

关于c - 如何在 environ 中使用 execvp/execlp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20059240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com