Shell.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * @Description:
  3. * @Version: 1.0
  4. * @Autor: lishengyin
  5. * @Date: 2022-01-11 17:03:06
  6. * @LastEditors: lishengyin
  7. * @LastEditTime: 2022-08-22 14:09:59
  8. */
  9. #include "Shell.h"
  10. pair<BOOL, string> CShell::exeShellCmd(IN const string &cmd, OUT INT *cmdReturnValue)
  11. {
  12. pid_t status; //pid_t 就是 int
  13. status = system(cmd.c_str()); //阶段1:创建子进程等准备工作,如果失败返回 -1
  14. if (-1 == status)
  15. {
  16. return make_pair(false, "阶段1:创建子进程等准备工作错误, 错误信息:" + string(strerror(errno)));
  17. }
  18. else
  19. {
  20. //阶段2:调用 /bin/sh 拉起脚本执行,如果脚本拉起失败或脚本未正常执行结束,则原因值被写入到 status 的低 8~15 比特位中。
  21. //不管脚本中返回什么值,是 0 还是非 0,都算正常执行结束。即使脚本不存在或没有执行权限,也都算正常执行结束。
  22. //如果脚本执行过程中被强制 kill 掉等情况则算异常结束。
  23. if (WIFEXITED(status))
  24. {
  25. if (nullptr != cmdReturnValue)
  26. {
  27. *cmdReturnValue = WEXITSTATUS(status); //获取脚本返回值,一般脚本或命令正确执行返回值是 0,执行错误返回其它值
  28. }
  29. return make_pair(true, "");
  30. }
  31. else
  32. {
  33. return make_pair(false, "阶段2:调用 /bin/sh 拉起脚本(命令)执行,脚本(命令)拉起失败或脚本(命令)未正常执行结束");
  34. }
  35. }
  36. } //exeShellCmd()
  37. pair<BOOL, string> CShell::exeShellCmd(IN const string &cmd, OUT vector<string> &results)
  38. {
  39. INT bufferSize = 10240; //10KB应该是非常充足了
  40. CHAR *buffer = new CHAR[bufferSize];
  41. FILE *pFile = NULL;
  42. if (NULL == (pFile = popen(cmd.c_str(), "r")))
  43. {
  44. return make_pair(false, "execute shell command error");
  45. }
  46. while (NULL != fgets(buffer, bufferSize, pFile))
  47. {
  48. buffer[strlen(buffer) - 1] = '\0'; //fgets() 会自动在末尾加入换行符,linux 下换行符就是 \n(LF),这里把自动添加的换行符去掉
  49. results.emplace_back(buffer);
  50. }
  51. delete[] buffer;
  52. pclose(pFile);
  53. return make_pair(true, "");
  54. } //exeShellCmd()