Get current program path and number of CPUs under Windows and Linux

Source: Internet
Author: User

[CPP]View Plaincopy
  1. #ifdef WIN32
  2. #include <Windows.h>
  3. #else
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #endif
  7. #include <assert.h>
  8. std::string Getcurrentapppath ()
  9. {
  10. #ifdef WIN32
  11. Char Path[max_path + 1] = {0};
  12. if (GetModuleFileName (NULL, PATH, MAX_PATH)! = 0)
  13. return std::string (path);
  14. #else
  15. char path[256] = {0};
  16. char filepath[256] = {0};
  17. char cmd[256] = {0};
  18. file* fp = NULL;
  19. //Set the proc path where the process is located
  20. sprintf (filepath, "/proc/%d", Getpid ());
  21. //Set current path to process path
  22. if (chdir (filepath)! =-1)
  23. {
  24. //Specify the shell command to execute
  25. snprintf (cmd, page, "Ls-l | grep exe |  awk ' {print $ *} ');
  26. if (fp = Popen (cmd,"R")) = = = NULL)
  27. {
  28. return std::string ();
  29. }
  30. //Read shell command execution result into string path
  31. if (fgets (path, sizeof (path)/sizeof (path[0]), fp) = = NULL)
  32. {
  33. Pclose (FP);
  34. return std::string ();
  35. }
  36. //popen Open FD must be pclose closed
  37. Pclose (FP);
  38. return std::string (path);
  39. }
  40. #endif
  41. return std::string ();
  42. }
  43. std::size_t getcpucount ()
  44. {
  45. #ifdef WIN32
  46. System_info SysInfo;
  47. GetSystemInfo (&sysinfo);
  48. return sysinfo.dwnumberofprocessors;
  49. #else
  50. Long cpu_num = sysconf (_SC_NPROCESSORS_ONLN);
  51. if (cpu_num = =-1)
  52. {
  53. ASSERT (false);
  54. return 0;
  55. }
  56. //See if the two are equal
  57. ASSERT (Cpu_num = = sysconf (_sc_nprocessors_conf));
  58. return cpu_num;
  59. #endif
  60. }

Get current program path and number of CPUs under Windows and Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.