windows和linux下获取当前程序路径以及cpu数

#ifdef WIN32
#include <Windows.h>
#else
#include <stdio.h>
#include <unistd.h>
#endif

#include <assert.h>

	std::string getCurrentAppPath()
	{
#ifdef WIN32
		char path[MAX_PATH + 1] = {0};
		if (GetModuleFileName(NULL, path, MAX_PATH) != 0)
			return std::string(path);
#else
		char 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);
		}
#endif
		return std::string();
	}

	std::size_t getCpuCount()
	{
#ifdef WIN32
		SYSTEM_INFO sysInfo;
		GetSystemInfo(&sysInfo);
		return sysInfo.dwNumberOfProcessors;
#else
		long 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
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值