1. execlp函數定義
int execlp(const char *file, const char *arg, ...);
參數說明:
file --文件名稱,如果包含“/”,則認爲路徑名,直接查找程序,否則,從PATH環境變量指定的路徑中查找程序。
arg --新程序啓動參數,每個arg都是非空的string,參數列表以NULL結束。
2. 問題思路及代碼
1)問題
使用execlp向新程序傳參時,當參數很多,需要逐個轉換成字符串,函數調用冗長繁瑣,在新程序中很難區分這些參數的意義。
2)思路
對所有參數進行序列化,將序列化後的字符串傳遞給新程序;新程序啓動後,獲取參數並反序列化,得到參數對象。
採用boost庫進行序列化。
3)部分代碼
processA啓動新程序processB,將ProcessExecArgs參數對象序列化後傳遞給processB:
ProcessExecArgs params;
params._a = 1;
params._b = 2;
params._c = "test";
execlp("processB", params.getSerializedStr().c_str(), (char*)0);
processB的main函數反序列化參數對象:
int main(int argc, char **argv)
{
if(argc < 1)
{
printf("error: argc < 1\n");
return 0;
}
ProcessExecArgs params;
params.initFromSerializedStr(argv[0]);
printf("a:%u, b:%lu, c:%s\n", params._a, params._b, params._c.c_str());
return 0;
}
參數結構體類:ProcessExecArgs
#include <string>
#include <iostream>
#include <sstream>
#include <boost/serialization/access.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
class ProcessExecArgs
{
public:
uint16_t _a;
uint64_t _b;
std::string _c;
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int /*version*/)
{
ar &_a;
ar &_b;
ar &_c;
}
std::string getSerializedStr()
{
std::ostringstream archiveStream;
boost::archive::text_oarchive archive(archiveStream);
archive << *this;
return archiveStream.str();
}
void initFromSerializedStr(const std::string &aData)
{
std::istringstream is(aData.c_str());
boost::archive::text_iarchive ia(is);
ia >> *this;
}
};