linux下獲取啓動參數的方法

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,會忽略掉雙引號。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章