c++ - 将参数传递给 exec*() 函数族的内存会发生什么变化?

标签 c++ memory exec

据我所知,当调用exec*() 时,旧进程的内存完全被新程序取代。但是,argv 等参数的内存呢?如果我有这样的代码,使用来自 C++ 数据结构(例如 std::string)的内存是否安全,或者它们是否会消失,破坏 argv

#include <unistd.h>
#include <string>
#include <string.h>
#include <vector>
#include <iostream>

void
execExample(const std::vector<std::string> &arguments)
{
  char **argv = new char *[arguments.size() + 2];
  char *path = "/path/to/my/executable";
  unsigned int idx = 0;

  argv[idx] = path;

  for (; ++idx < arguments.size() + 1; ) {
    argv[idx] = const_cast<char *>(arguments[idx - 1].c_str());
  }

  argv[idx] = 0;

  execv(path, argv); // Does not return if successful.

  std::cerr << "exec failed: " << strerror(errno) << ".\n";
}

最佳答案

来自execv man page :

The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer. [Emphasis added]

因此,您提供了一个空终止 C 字符串的空终止数组。手册页没有明确说明内存发生了什么,但大概是将字符串复制到新进程,就像通过 strcpy 一样,并将新指针提供给 新进程的 main。因为 execv 不可能知道关于这些字符串的任何上下文(它们是静态的吗?本地的?malloc'd?),在极端情况下对我来说数组似乎不太可能指针将被浅层复制到新进程

为了解决您的确切问题,这意味着几乎任何以空字符结尾的 char* 来源(包括 std::string,通过 str. c_str()str.data()) 可用作传递给 execv 的数组的一部分。值得注意的是,在 C++11 之前,std::strings 不需要以 null 终止,只要 c_str成员返回一个指向空终止字符串的指针。我不知道 std::string 的任何实现都不是空终止的,但值得注意的是,与 c 字符串 std::string 不同可能包含 \0 个字符作为字符串数据的一部分,而不是作为终止符。

作为旁注,execv 调用将立即用新进程替换调用进程。这意味着 C++ 析构函数不会被调用。std::stringstd::vector 和任何其他动态内存的情况下,这没关系——所有分配的内存都会自动回收,所以不会有任何泄漏。然而,其他副作用不会发生,std::fstream 不会关闭它们的文件,等等。通常这无关紧要,因为具有严重副作用的析构函数很差设计实践,但这是需要注意的事情。

关于c++ - 将参数传递给 exec*() 函数族的内存会发生什么变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222327/

相关文章:

docker - 错误: No such container while using docker exec command

c++ - 重载 << 运算符 C++ - 指向类的指针

iphone - iPhone OS 应用程序的可用内存

c++ - 对 CMake find_path 提示使用正则表达式

C++内存泄漏会导致内存错误吗?

linux - 连续的内存块如何减少内存访问时间?

php - 对使用 proc_open 打开的进程进行多次写入

fork 后子进程无法正常工作

c++ - 复制结构的一部分

c++ - 矩阵相乘时的段错误