我正在处理一些遗留代码。它在CentOS 7系统上工作得很好。args阵列在Rocky 8.4和Ubuntu 20.04系统上都会被使用。我简化了问题并添加了打印语句。execv()正在启动另一个程序。去执政官的火箭筒都搞砸了。没有分叉,代码将按预期的方式工作。不知所措。
我有两个简单的测试程序,其中一个什么都不做。
test9.cpp
int main(){}和test10.cpp
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
int main()
{
std::vector<std::string> stringArgs;
std::string a{"./test9.x"};
std::string b{"test10.cpp"};
stringArgs.push_back(a);
stringArgs.push_back(b);
char* args[stringArgs.size()+1];
if(fork() == 0){
for(uint8_t i = 0; i < stringArgs.size(); i++) {
std::string tmp(stringArgs[i]);
args[i] = const_cast<char*>(tmp.c_str());
std::cout << "\n\t"<<args[i]<<"'\n\n";
}
std::cout << "\n\t"<<args[0]<<"'\n\n";
std::cout << "\n\t"<<args[1]<<"'\n\n";
// last argument has to be NULL
args[stringArgs.size()] = NULL;
execv(args[0],&args[0]);
std::cout << "\n\tERROR: Could not run '"<<args[0]<<"'\n\n";
}
else
std::cout<<"parent\n";
}g++ -o test9.x test9.cpp; g++ -o test10.x test10.cpp
在CentOS 7上我得到:
$ ./test10.x
./test9.x
test10.cpp
./test9.x
test10.cpp
parent在Rocky Linux8.4和Ubuntu20.04上,我都知道这一点。注意,test9.x在for循环之后被test10.cpp替换。
./test10.x
parent
./test9.x
test10.cpp
test10.cpp
test10.cpp
ERROR: Could not run test10.cpp发布于 2022-05-06 20:15:57
THis回路
for(uint8_t i = 0; i < stringArgs.size(); i++) {
std::string tmp(stringArgs[i]);
args[i] = const_cast<char*>(tmp.c_str());
std::cout << "\n\t"<<args[i]<<"'\n\n";
}正在创建指向堆栈上的临时指针的数组,或定义了std::string部分的内部实现。
代之而行
for(uint8_t i = 0; i < stringArgs.size(); i++) {
args[i] = strdup(stringArgs[i]);
std::cout << "\n\t"<<args[i]<<"'\n\n";
}https://stackoverflow.com/questions/72146860
复制相似问题