windows和linux下擷取當前程式路徑以及cpu數

來源:互聯網
上載者:User
#ifdef WIN32#include <Windows.h>#else#include <stdio.h>#include <unistd.h>#endif#include <assert.h>std::string getCurrentAppPath(){#ifdef WIN32char path[MAX_PATH + 1] = {0};if (GetModuleFileName(NULL, path, MAX_PATH) != 0)return std::string(path);#elsechar path[256] = {0};char filepath[256] = {0};char cmd[256] = {0};FILE* fp = NULL;// 設定進程所在proc路徑sprintf(filepath, "/proc/%d", getpid());// 將當前路徑設為進程路徑if(chdir(filepath) != -1){//指定待執行的shell 命令snprintf(cmd, 256, "ls -l | grep exe | awk '{print $10}'");if((fp = popen(cmd,"r")) == NULL){return std::string();}//讀取shell命令執行結果到字串path中if (fgets(path, sizeof(path)/sizeof(path[0]), fp) == NULL){pclose(fp);return std::string();}//popen開啟的fd必須要pclose關閉pclose(fp);return std::string(path);}#endifreturn std::string();}std::size_t getCpuCount(){#ifdef WIN32SYSTEM_INFO sysInfo;GetSystemInfo(&sysInfo);return sysInfo.dwNumberOfProcessors;#elselong cpu_num = sysconf(_SC_NPROCESSORS_ONLN);if (cpu_num == -1){    assert(false);    return 0;}// 看兩者是否相等        assert(cpu_num == sysconf(_SC_NPROCESSORS_CONF));        return cpu_num;#endif}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.