简介
使用c++开发程序时,虽然c11和boost提供一些跨平台的特性支持,但是涉及到操作系统层面的一些功能还是不能有效地跨平台。
本文旨在提炼出这些经常使用的,但又不能跨平台的功能,形成一个工具库,方便以后使用。
代码结构
该工具库共由两个文件组成: cross_platform_utils.h
和cross_platform_utils.cpp
。
h文件如下:
#ifndef _CROSS_PLATFORM_UTILS_
#define _CROSS_PLATFORM_UTILS_
#include <string>
#if defined _WIN32 || defined _WIN64
#define FILE_SEP "\\"
#define __FILENAME__ (strrchr(__FILE__, '\\') ? (strrchr(__FILE__, '\\') + 1) : __FILE__)
#else
#define FILE_SEP "/"
#define __FILENAME__ (strrchr(__FILE__, '/') ? (strrchr(__FILE__, '/') + 1) : __FILE__)
#endif
#define FILE_FUN __FILENAME__ << ":" <<__FUNCTION__ << ":" << __LINE__ << "|"
#define FILE_FUN_STR string(__FILENAME__) + ":" + string(__FUNCTION__) + :" + string(__LINE__) + "|"
class CrossPlatformUtils
{
public:
/*
* 获取当前线程唯一标识:tid
* 跨平台实现,与unix下的top显示和windows下的process explore查看的线程id一致
*/
static long GetTid();
static bool IsProcessRunning(const std::string& process);
};
#endif // !_CROSS_PLATFORM_UTILS_
目前实现了两个接口,分别是获取线程id和检测进程是否已经运行。
cpp文件可以直接参考github代码:cross_platform_utils
最后
把轮子放在一起,就可以更好地专注于业务,而不必为这些细节分神。
对于该项目中的任何问题,欢迎issue。