main函数并不总是可见。
最近的一个项目就因为要在提供给其他程序调用的库中获取启动参数困扰了几天。
Windows下很简单,linux下百度是找不到方法的。我下了班就懒得连VPN去谷歌了。
直接上代码。
#include <iostream>
#include <string>
#include <sstream>
#include <unistd.h>
#include <vector>
#include <cstring>
static const std::string system(const std::string& cmd)
{
char* outcome = nullptr;
static const unsigned int minBufferSize = 100;
unsigned int bufferSize = minBufferSize;
unsigned int totalBytes = 0;
// execute cmd, store the output into pipe
FILE* pipe = popen(cmd.c_str(), "r");
// write output to outcome
int readBytes = 0;
do
{
bufferSize *= 2;
char *buf = new char[bufferSize];
memset(buf, '\0', sizeof(char)*bufferSize);
readBytes = fread(buf, sizeof(char), bufferSize, pipe);
totalBytes += readBytes;
if(totalBytes==0)
break;
if(!outcome)
{
outcome = new char[readBytes];
memcpy(outcome, buf, readBytes);
}
else
{
char* tmp = outcome;
outcome = new char[totalBytes];
memcpy(outcome, tmp, totalBytes-readBytes);
memcpy(outcome+totalBytes-readBytes, buf, readBytes);
delete[] tmp;
}
delete[] buf;
}while(readBytes >= bufferSize);
// close pipe
pclose(pipe);
// add '\0' to the end of the string,
// put it into a std::string object.
if(outcome)
{
char *tmp = outcome;
outcome = new char[totalBytes + 1];
memcpy(outcome, tmp, totalBytes);
memcpy(outcome + totalBytes, "\0", 1);
delete[] tmp;
}
std::string output(outcome);
delete[] outcome;
// return output
return std::move(output);
}
static std::vector<std::string> GetBootArguments()
{
// boot arguments
std::vector<std::string> bootArguments;
// get pid
std::string sPid;
long pid = getpid();
std::stringstream l2s;
l2s << pid;
l2s >> sPid;
// read /proc/self/cmdline
std::string command("ps -o pid,args | grep ");
command += sPid + " | grep -v grep";
std::string tmp;
std::string output = system(command);
std::stringstream split(output);
split >> sPid;
while(split>>tmp)
bootArguments.push_back(std::move(tmp));
return std::move(bootArguments);
}
int main()
{
auto argv = GetBootArguments();
for(auto& str: argv)
std::cout << str << std::endl;
return 0;
}
这个办法目前有个已知的bug,会忽略掉双引号。