linux c++ 得到 指定进程名 线程数

悠悠 2021-09-02 08:03 1081阅读 0赞

代码如下:

  1. #include<iostream>
  2. #include<stdlib.h>
  3. #include<stdio.h>
  4. #include<string.h>
  5. using namespace std;
  6. int getProcessIdByExeName(const char* pName)
  7. {
  8. char buf[256] = {0};
  9. snprintf(buf,sizeof(buf),"ps -ef | grep \"%s\" | grep -v grep | awk '{print $2}'",pName);
  10. FILE* fp = popen(buf,"r");
  11. if(fp == NULL)
  12. {
  13. printf("popen failed, buf = %s",buf);
  14. return -1;
  15. }
  16. char oBuf[256] = {0};
  17. fgets(oBuf,256,fp);
  18. if(strlen(oBuf) == 0)
  19. {
  20. pclose(fp);
  21. return -1;
  22. }
  23. oBuf[strlen(oBuf)-1] = '\0';
  24. pclose(fp);
  25. return atoi(oBuf);
  26. }
  27. int getThread(const std::string& strSrvName)
  28. {
  29. int iPid = -1;
  30. iPid = getProcessIdByExeName(strSrvName.c_str());
  31. if(iPid < 0)
  32. {
  33. printf("get pid faild [%s]",strSrvName.c_str());
  34. return -1;
  35. }
  36. char szFileName[64] = {0};
  37. FILE* fd =NULL;
  38. char szLineBuff[512] = { 0 };
  39. sprintf(szFileName, "/proc/%ld/status", iPid);
  40. fd = fopen(szFileName, "r");
  41. if(fd == NULL)
  42. {
  43. printf("open file %s failed",szFileName);
  44. return -1;
  45. }
  46. int iThread = -1;
  47. while (fgets(szLineBuff, sizeof(szLineBuff), fd) != NULL)
  48. {
  49. char szName[64] = {0};
  50. int iValue = 0;
  51. sscanf(szLineBuff, "%s", szName);//%s遇空格停止
  52. // 进程使用的线程数
  53. if (strcmp(szName, "Threads:") == 0)
  54. {
  55. sscanf(szLineBuff, "%s %d", szName, &iValue);
  56. iThread = iValue;
  57. break;
  58. }
  59. }
  60. fclose(fd);
  61. return iThread;
  62. }
  63. int main()
  64. {
  65. int ret=getThread("alarm");
  66. printf("alarm exe's threads =%d\n",ret);
  67. return 0;
  68. }

发表评论

表情:
评论列表 (有 0 条评论,1081人围观)

还没有评论,来说两句吧...

相关阅读