【发布时间】:2017-11-03 00:04:58
【问题描述】:
我有一个在 C++ STL 容器中存储 file、argv 和 envp 的结构。该结构还具有将它们转换为 execve 调用的 c 样式指针的方法。
struct Foo {
std::string file;
std::vector <std::string> argv;
std::unordered_map <std::string, std::string> envp;
inline auto c_file() const;
inline auto c_argv() const;
inline auto c_envp() const;
}
// Function: c_file
inline auto Foo::c_file() const {
return file.c_str();
}
// Function: c_argv
inline auto Foo::c_argv() const {
auto ptr = std::make_unique<char*[]>(argv.size() + 1);
for(size_t i=0; i<argv.size(); ++i) {
ptr[i] = const_cast<char*>(argv[i].c_str());
}
ptr[argv.size()] = nullptr;
return ptr;
}
// Function: c_envp
inline auto Foo::c_envp() const {
std::unique_ptr<char*, std::function<void(char**)>> ptr(
new char*[envp.size() + 1],
[sz=envp.size()+1](char** ptr) {
for(size_t i=0; i<sz; ++i) {
delete [] ptr[i];
}
delete [] ptr;
}
);
auto idx = size_t{0};
for(const auto& kvp : envp) {
auto entry = kvp.first + "=" + kvp.second;
ptr.get()[idx] = new char[entry.size() + 1];
::strncpy(ptr.get()[idx], entry.c_str(), entry.size() + 1);
++idx;
}
ptr.get()[idx] = nullptr;
return ptr;
}
在我的程序中,我使用如下方式调用execve。
void in_parent_process(const Foo& foo) {
char stack[1024*1024];
::clone(child_entry, stack + 1024*1024, myflags, &foo)
}
void child_entry(void* ptr) {
const auto& foo = *static_cast<Foo*>(ptr);
::execve(foo.c_file(), foo.c_argv().get(), foo.c_envp().get());
}
但是,对execve 的调用有时会挂起而没有任何响应。这使我的父进程无法与子进程同步(通过管道关闭执行)。我在这里使用unique_ptr 的想法有什么问题吗?还是我对将堆栈设置为clone 调用的理解有问题?
【问题讨论】: