YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
SystemInfo.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-FileCopyrightText: 2006-2010 RobotCub Consortium
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
8
9#include <yarp/os/Os.h>
11
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15
16using namespace yarp::os;
17
18#if defined(__linux__)
19# include <arpa/inet.h>
20# include <ifaddrs.h>
21# include <linux/if.h>
22# include <netinet/in.h>
23# include <pwd.h>
24# include <sys/ioctl.h>
25# include <sys/socket.h>
26# include <sys/statvfs.h>
27# include <sys/types.h>
28# include <sys/utsname.h>
29# include <unistd.h>
30
31extern char** environ;
32
33#elif defined(__APPLE__)
34# include <mach/mach.h>
35# include <pwd.h>
36# include <sstream>
37# include <sys/mount.h>
38# include <sys/param.h>
39# include <sys/sysctl.h>
40# include <sys/types.h>
41# include <unistd.h>
42
43namespace {
44
45YARP_OS_LOG_COMPONENT(SYSTEMINFO, "yarp.os.SystemInfo")
46
47} // namespace
48
49#endif
50
51#if defined(_WIN32)
52# include <Lmcons.h>
53# include <comdef.h> // for using bstr_t class
54# include <psapi.h>
55# include <shlobj.h>
56# include <windows.h>
57//#define _WIN32_DCOM
58# include <wbemidl.h>
59# if (defined(WINVER)) && (WINVER >= 0x0502)
60# include <pdh.h>
61# include <pdhmsg.h>
62# pragma comment(lib, "pdh.lib")
63# pragma comment(lib, "psapi.lib") // for get proocess name for pid
64# pragma comment(lib, "wbemuuid.lib") // for get process arguments from pid
65# endif
66
68# include <yarp/os/Semaphore.h>
69
70# include <vector>
71
72
73static void enableCpuLoadCollector();
74static void disableCpuLoadCollector();
75
76#endif
77
78#if defined(__linux__)
79SystemInfo::capacity_t getMemEntry(const char* tag, const char* bufptr)
80{
81 char* tail;
83 size_t len = strlen(tag);
84 while (bufptr != nullptr) {
85 if (*bufptr == '\n') {
86 bufptr++;
87 }
88 if (strncmp(tag, bufptr, len) == 0) {
89 retval = strtol(bufptr + len, &tail, 10);
90 if (tail == bufptr + len) {
91 return -1;
92 }
93 return retval;
94 }
95 bufptr = strchr(bufptr, '\n');
96 }
97 return -1;
98}
99
100
101bool getCpuEntry(const char* tag, const char* buff, std::string& value)
102{
103 if (strlen(buff) <= strlen(tag)) {
104 return false;
105 }
106
107 if (strncmp(buff, tag, strlen(tag)) != 0) {
108 return false;
109 }
110
111 const char* pos1 = strchr(buff, ':');
112 if (pos1 == nullptr) {
113 return false;
114 }
115
116 while ((*pos1 != '\0') && ((*pos1 == ' ') || (*pos1 == ':') || (*pos1 == '\t'))) {
117 pos1++;
118 }
119 const char* pos2 = buff + strlen(buff) - 1;
120 while ((*pos2 != ':') && ((*pos2 == ' ') || (*pos2 == '\n'))) {
121 pos2--;
122 }
123 if (pos2 < pos1) {
124 return false;
125 }
126 value = std::string(pos1, pos2 - pos1 + 1);
127 return true;
128}
129#endif
130
131
132#if defined(_WIN32)
134{
135public:
138 {
139 firstRun = true;
140 load.cpuLoad1 = 0.0;
141 load.cpuLoad5 = 0.0;
142 load.cpuLoad15 = 0.0;
143 load.cpuLoadInstant = (int)0;
144 }
145
147 {
148 }
149
150 void run()
151 {
152 sem.wait();
153 load.cpuLoadInstant = (int)phdCpuLoad();
154 samples.push_back(load.cpuLoadInstant);
155 if (samples.size() > 180)
156 samples.erase(samples.begin());
157
158 std::vector<int>::reverse_iterator rti;
159 int sum = 0;
160 int n = 0;
161 for (rti = samples.rbegin(); rti < samples.rend(); ++rti) {
162 sum += (*rti);
163 n++;
164 // every 1min
165 if (n < 12)
166 load.cpuLoad1 = (double)(sum / n) / 100.0;
167 // every 5min
168 if (n < 60)
169 load.cpuLoad5 = (double)(sum / n) / 100.0;
170 // every 15min
171 load.cpuLoad15 = (double)(sum / n) / 100.0;
172 }
173 sem.post();
174 }
175
177 {
178 sem.wait();
180 sem.post();
181 return ld;
182 }
183
184 //bool threadInit()
185 //void threadRelease()
186private:
187# if (defined(WINVER)) && (WINVER >= 0x0502)
188 double phdCpuLoad()
189 {
190 DWORD ret;
191 if (firstRun) {
192 phdStatus = PdhOpenQuery(nullptr, 0, &hPhdQuery);
194 return 0;
195
196 PdhAddCounter(hPhdQuery, TEXT("\\Processor(_Total)\\% Processor Time"), 0, &phdCounter);
198 firstRun = false;
199 return 0;
200 }
201
204 return 0;
207 &ret,
208 &phdFmtValue);
210 return 0;
211 return phdFmtValue.doubleValue;
212 }
213# else
214 double phdCpuLoad()
215 {
216 return 0.0;
217 }
218# endif
219
220private:
221# if (defined(WINVER)) && (WINVER >= 0x0502)
226# endif
227 bool firstRun;
229 std::vector<int> samples;
231};
232
233static CpuLoadCollector* globalLoadCollector = nullptr;
234
236{
237 if (globalLoadCollector == nullptr) {
239 globalLoadCollector->start();
240 }
241}
242
244{
246 globalLoadCollector->stop();
247 delete globalLoadCollector;
248 globalLoadCollector = nullptr;
249 }
250}
251
252#endif
253
254
256{
258 memory.totalSpace = 0;
259 memory.freeSpace = 0;
260
261#if defined(_WIN32)
263 statex.dwLength = sizeof(statex);
265 memory.totalSpace = (capacity_t)(statex.ullTotalPhys / 1048576); //in Mb
266 memory.freeSpace = (capacity_t)(statex.ullAvailPhys / 1048576); //in Mb
267 }
268#endif
269
270#if defined(__linux__)
271 char buffer[128];
272 FILE* procmem = fopen("/proc/meminfo", "r");
273 if (procmem != nullptr) {
274 while (fgets(buffer, 128, procmem) != nullptr) {
275 capacity_t ret;
276 if ((ret = getMemEntry("MemTotal:", buffer)) > 0) {
277 memory.totalSpace = ret / 1024;
278 }
279
280 if ((ret = getMemEntry("MemFree:", buffer)) > 0) {
281 memory.freeSpace = ret / 1024;
282 }
283 }
285 }
286#elif defined(__APPLE__)
287
292
294 count = HOST_VM_INFO64_COUNT;
296 //These seem to return the # of pages
297 natural_t activePages = vm_stats.active_count + vm_stats.wire_count;
298 natural_t inactivePages = vm_stats.inactive_count + vm_stats.free_count;
300
302 int64_t freeSpace = inactivePages * page_size;
303
304 memory.totalSpace = total / 1024;
305 memory.freeSpace = freeSpace / 1024;
306 }
307
308#endif
309
310
311 return memory;
312}
313
314
316{
319 storage.freeSpace = 0;
320
321#if defined(_WIN32)
322
325 std::string strHome = getUserInfo().homeDir;
326 if (strHome.empty())
327 strHome = "C:\\";
331 }
332#endif
333
334#if defined(__linux__)
335 std::string strHome = getUserInfo().homeDir;
336 if (strHome.empty()) {
337 strHome = "/home";
338 }
339
340 struct statvfs vfs;
341 if (statvfs(strHome.c_str(), &vfs) == 0) {
342 storage.totalSpace = (int)(vfs.f_blocks * vfs.f_bsize / (1048576)); // in MB
343 storage.freeSpace = (int)(vfs.f_bavail * vfs.f_bsize / (1048576)); // in MB
344 }
345
346#endif
347
348#if defined(__APPLE__)
349 std::string strHome = getUserInfo().homeDir;
350 if (strHome.empty())
351 strHome = "/";
352
353 struct statfs vfs;
354 if (statfs(strHome.c_str(), &vfs) == 0) {
355 storage.totalSpace = (int)(vfs.f_blocks * vfs.f_bsize / (1048576)); // in MB
356 storage.freeSpace = (int)(vfs.f_bavail * vfs.f_bsize / (1048576)); // in MB
357 }
358#endif
359
360 return storage;
361}
362
363/*
364SystemInfo::NetworkInfo SystemInfo::getNetworkInfo()
365{
366 NetworkInfo network;
367
368#if defined(__linux__)
369
370 struct ifaddrs * ifAddrStruct=nullptr;
371 struct ifaddrs * ifa=nullptr;
372 void * tmpAddrPtr=nullptr;
373
374 getifaddrs(&ifAddrStruct);
375 for (ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next)
376 {
377 if (ifa ->ifa_addr->sa_family == AF_INET)
378 {
379 // is a valid IP4 Address
380 tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
381 char addressBuffer[INET_ADDRSTRLEN];
382 const char* ret = inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
383 if (ret && (strcmp(ifa->ifa_name, "eth0") == 0))
384 network.ip4 = addressBuffer;
385 }
386 else if (ifa->ifa_addr->sa_family == AF_INET6)
387 {
388 // is a valid IP6 Address
389 tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
390 char addressBuffer[INET6_ADDRSTRLEN];
391 const char* ret = inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
392 if (ret && (strcmp(ifa->ifa_name, "eth0") == 0))
393 network.ip6 = addressBuffer;
394 }
395 }
396
397 if (ifAddrStruct)
398 freeifaddrs(ifAddrStruct);
399
400 // getting mac addrress
401 struct ifreq ifr;
402 struct ifreq *IFR;
403 struct ifconf ifc;
404 char buf[1024];
405 int s;
406 bool found = false;
407
408 if ( (s = socket(AF_INET, SOCK_DGRAM, 0)) == -1 )
409 return network;
410
411 ifc.ifc_len = sizeof(buf);
412 ifc.ifc_buf = buf;
413 ioctl(s, SIOCGIFCONF, &ifc);
414 IFR = ifc.ifc_req;
415 for (int i = ifc.ifc_len/sizeof(struct ifreq); --i >= 0; IFR++)
416 {
417 strcpy(ifr.ifr_name, IFR->ifr_name);
418 if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0)
419 {
420 if (!(ifr.ifr_flags & IFF_LOOPBACK))
421 {
422 if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0)
423 {
424 found = true;
425 break;
426 }
427 }
428 }
429 }
430 close(s);
431
432 if (found)
433 {
434 unsigned char addr[6];
435 char mac[32];
436 bcopy(ifr.ifr_hwaddr.sa_data, addr, 6);
437 sprintf(mac, "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x",
438 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
439 network.mac = mac;
440 }
441
442#endif
443 return network;
444}
445*/
446
447
449{
451 processor.cores = 0;
452 processor.frequency = 0.0;
453 processor.family = 0;
456
457#if defined(_WIN32)
460 switch (sysinf.wProcessorArchitecture) {
462 processor.architecture = "X64";
463 break;
464 }
466 processor.architecture = "Intel Itanium-based";
467 break;
468 }
470 processor.architecture = "X86";
471 break;
472 }
473 default:
474 processor.architecture = "Unknown";
475 };
476 processor.siblings = sysinf.dwNumberOfProcessors;
477 processor.modelNumber = sysinf.dwProcessorType;
478 switch (sysinf.dwProcessorType) {
479 case PROCESSOR_INTEL_386: {
480 processor.model = "PROCESSOR_INTEL_386";
481 break;
482 }
483 case PROCESSOR_INTEL_486: {
484 processor.model = "PROCESSOR_INTEL_486";
485 break;
486 }
488 processor.model = "PROCESSOR_INTEL_PENTIUM";
489 break;
490 }
492 processor.model = "PROCESSOR_INTEL_IA64";
493 break;
494 }
495 case PROCESSOR_AMD_X8664: {
496 processor.model = "PROCESSOR_AMD_X8664";
497 break;
498 }
499 };
500
501 DWORD dwMHz;
502 DWORD BufSize = sizeof(DWORD);
503 HKEY hKey;
505 "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
506 0,
507 KEY_READ,
508 &hKey)
509 == ERROR_SUCCESS) {
510 RegQueryValueEx(hKey, "~MHz", nullptr, nullptr, (LPBYTE)&dwMHz, &BufSize);
513 }
514
515 // TODO: this should be fixed to obtain correct number of physical cores
516 processor.cores = 1;
517
518#endif
519
520#if defined(__linux__)
521 char buffer[128];
522 FILE* proccpu = fopen("/proc/cpuinfo", "r");
523 if (proccpu != nullptr) {
524 while (fgets(buffer, 128, proccpu) != nullptr) {
525 std::string value;
526 if (getCpuEntry("model", buffer, value) && !getCpuEntry("model name", buffer, value)) {
527 processor.modelNumber = atoi(value.c_str());
528 }
529 if (getCpuEntry("model name", buffer, value)) {
530 processor.model = value;
531 }
532 if (getCpuEntry("vendor_id", buffer, value)) {
533 processor.vendor = value;
534 }
535 if (getCpuEntry("cpu family", buffer, value)) {
536 processor.family = atoi(value.c_str());
537 }
538 if (getCpuEntry("cpu cores", buffer, value)) {
539 processor.cores = atoi(value.c_str());
540 }
541 if (getCpuEntry("siblings", buffer, value)) {
542 processor.siblings = atoi(value.c_str());
543 }
544 if (getCpuEntry("cpu MHz", buffer, value)) {
545 processor.frequency = atof(value.c_str());
546 }
547 }
549 }
550
551 struct utsname uts;
552 if (uname(&uts) == 0) {
553 processor.architecture = uts.machine;
554 }
555#elif defined(__APPLE__)
556 // std::string architecture;
557
558 int mib[] = {CTL_HW, HW_CPU_FREQ};
559 int64_t value = 0;
560 size_t length = sizeof(value);
561
562 if (!sysctl(mib, 2, &value, &length, nullptr, 0)) {
563 processor.frequency = value / 1e+6; //this is in Hz. What is the expected frequency?
564 }
565
566 if (!sysctlbyname("hw.logicalcpu", &value, &length, nullptr, 0)) {
567 processor.cores = value; //this is the number of cores
568 //or cpus: hw.physicalcpu
569 }
570
571 char buff[513];
572 size_t buffLen = 512;
573 if (!sysctlbyname("machdep.cpu.vendor", buff, &buffLen, nullptr, 0)) {
574 processor.vendor = buff; //this is the number of cores
575 //or cpus: hw.physicalcpu
576 }
577 buffLen = 512;
578 if (!sysctlbyname("machdep.cpu.brand_string", buff, &buffLen, nullptr, 0)) {
579 processor.model = buff; //this is the number of cores
580 //or cpus: hw.physicalcpu
581 }
582 if (!sysctlbyname("machdep.cpu.family", &value, &length, nullptr, 0)) {
583 processor.family = value; //this is the number of cores
584 //or cpus: hw.physicalcpu
585 }
586 if (!sysctlbyname("machdep.cpu.model", &value, &length, nullptr, 0)) {
587 processor.modelNumber = value; //this is the number of cores
588 //or cpus: hw.physicalcpu
589 }
590
591
592#endif
593 return processor;
594}
595
608
610{
611 return SystemInfoData::read(connection);
612}
613
615{
616 //this->updateSystemInfo();
617 return SystemInfoData::write(connection);
618}
619
621{
623
624#if defined(_WIN32)
625 platform.name = "Windows";
627 osver.dwOSVersionInfoSize = sizeof(osver);
629 char buff[64];
630 sprintf(buff, "%d.%d", osver.dwMajorVersion, osver.dwMinorVersion);
631 platform.release = buff;
632 platform.codename = buff;
633 if ((osver.dwMajorVersion == 10) && (osver.dwMinorVersion == 0) && (osver.wProductType == VER_NT_WORKSTATION)) {
634 platform.distribution = "10";
635 } else if ((osver.dwMajorVersion == 10) && (osver.dwMinorVersion == 0) && (osver.wProductType != VER_NT_WORKSTATION)) {
636 platform.distribution = "Server 2016";
637 } else if ((osver.dwMajorVersion == 6) && (osver.dwMinorVersion == 2) && (osver.wProductType == VER_NT_WORKSTATION)) {
638 platform.distribution = "8.1";
639 } else if ((osver.dwMajorVersion == 6) && (osver.dwMinorVersion == 3) && (osver.wProductType != VER_NT_WORKSTATION)) {
640 platform.distribution = "Server 2012 R2";
641 } else if ((osver.dwMajorVersion == 6) && (osver.dwMinorVersion == 2) && (osver.wProductType == VER_NT_WORKSTATION)) {
643 } else if ((osver.dwMajorVersion == 6) && (osver.dwMinorVersion == 2) && (osver.wProductType != VER_NT_WORKSTATION)) {
644 platform.distribution = "Server 2012";
645 } else if ((osver.dwMajorVersion == 6) && (osver.dwMinorVersion == 1) && (osver.wProductType == VER_NT_WORKSTATION)) {
647 } else if ((osver.dwMajorVersion == 6) && (osver.dwMinorVersion == 1) && (osver.wProductType != VER_NT_WORKSTATION)) {
648 platform.distribution = "Server 2008 R2";
649 } else if ((osver.dwMajorVersion == 6) && (osver.dwMinorVersion == 0) && (osver.wProductType == VER_NT_WORKSTATION)) {
650 platform.distribution = "Vista";
651 } else if ((osver.dwMajorVersion == 6) && (osver.dwMinorVersion == 0) && (osver.wProductType != VER_NT_WORKSTATION)) {
652 platform.distribution = "Server 2008";
653 } else if ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 2)) {
654 platform.distribution = "Server 2003";
655 // } else if ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 2) && (osver.wSuiteMask & VER_SUITE_WH_SERVER)) {
656 // platform.distribution = "Home Server";
657 // } else if ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 2) && (GetSystemMetrics(SM_SERVERR2) != 0)) {
658 // platform.distribution = "Server 2003 R2";
659 } else if ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 2) && (osver.wProductType == VER_NT_WORKSTATION)) /* &&(osver.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)*/ {
660 platform.distribution = "XP Professional x64 Edition";
661 } else if ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 1)) {
662 platform.distribution = "XP";
663 } else if ((osver.dwMajorVersion == 5) && (osver.dwMinorVersion == 0)) {
664 platform.distribution = "2000";
665 }
666 }
667
668 const char* a = GetEnvironmentStrings();
670 size_t prev = 0;
671 for (size_t i = 0;; i++) {
672 if (a[i] == '\0') {
673 std::string tmpVariable(a + prev, a + i);
674 size_t equalsSign = tmpVariable.find("=");
675 if (equalsSign != std::string::npos && equalsSign != 0) // among environment variables there are DOS-related ones that start with a =
676 {
677 tempProperty.put(tmpVariable.substr(0, equalsSign), tmpVariable.substr(equalsSign + 1));
678 }
679 prev = i + 1;
680 if (a[i + 1] == '\0') {
681 break;
682 }
683 }
684 }
686
687#endif
688
689#if defined(__linux__)
690 struct utsname uts;
691 if (uname(&uts) == 0) {
692 platform.name = uts.sysname;
694 } else {
695 platform.name = "Linux";
696 }
697
698 char buffer[128];
699 FILE* release = popen("lsb_release -ric", "r");
700 if (release != nullptr) {
701 while (fgets(buffer, 128, release) != nullptr) {
702 std::string value;
703 if (getCpuEntry("Distributor ID", buffer, value)) {
704 platform.distribution = value;
705 }
706 if (getCpuEntry("Release", buffer, value)) {
707 platform.release = value;
708 }
709 if (getCpuEntry("Codename", buffer, value)) {
710 platform.codename = value;
711 }
712 }
713 pclose(release);
714 }
715
716 char* varChar = *environ;
718 for (int i = 0; varChar != nullptr; i++) {
719 std::string tmpVariable(varChar);
720 size_t equalsSign = tmpVariable.find('=');
721 if (equalsSign != std::string::npos) {
722 tempProperty.put(tmpVariable.substr(0, equalsSign), tmpVariable.substr(equalsSign + 1));
723 }
724 varChar = *(environ + i);
725 }
727
728#endif
729
730#if defined(__APPLE__)
731
732 char buff[513];
733 size_t buffLen = 512;
734 if (!sysctlbyname("kern.ostype", buff, &buffLen, nullptr, 0)) {
735 platform.name = buff;
736 }
737
738 if (!sysctlbyname("kern.osrelease", buff, &buffLen, nullptr, 0)) {
739 platform.release = buff;
740 }
741
742#endif
743 return platform;
744}
745
746
748{
750 user.userID = 0;
751
752#if defined(_WIN32)
753 char path[MAX_PATH + 1];
754 if (SHGetFolderPathA(nullptr, CSIDL_PROFILE, nullptr, 0, path) == S_OK)
755 user.homeDir = path;
756
757 char username[UNLEN + 1];
758 DWORD nsize = UNLEN + 1;
759 if (GetUserName(username, &nsize)) {
762 }
763#endif
764
765#if defined(__linux__) || defined(__APPLE__)
766 struct passwd* pwd = getpwuid(getuid());
767 user.userID = getuid();
768 if (pwd != nullptr) {
769 user.userName = pwd->pw_name;
770 user.realName = pwd->pw_gecos;
771 user.homeDir = pwd->pw_dir;
772 }
773#endif
774 return user;
775}
776
777
779{
781 load.cpuLoad1 = 0.0;
782 load.cpuLoad5 = 0.0;
783 load.cpuLoad15 = 0.0;
785
786#if defined(_WIN32)
788 load = globalLoadCollector->getCpuLoad();
789 int siblings = getProcessorInfo().siblings;
790 if (siblings > 1) {
791 load.cpuLoad1 *= siblings;
792 load.cpuLoad5 *= siblings;
793 load.cpuLoad15 *= siblings;
794 }
795 }
796#endif
797
798#if defined(__linux__)
799 FILE* procload = fopen("/proc/loadavg", "r");
800 if (procload != nullptr) {
801 char buff[128];
802 int ret = fscanf(procload, "%lf %lf %lf %127s", &(load.cpuLoad1), &(load.cpuLoad5), &(load.cpuLoad15), buff);
803 if (ret > 0) {
804 char* tail = strchr(buff, '/');
805 if ((tail != nullptr) && (tail != buff)) {
806 load.cpuLoadInstant = (int)(strtol(buff, &tail, 0) - 1);
807 }
808 }
810 }
811#endif
812
813#if defined(__APPLE__)
814
817
819 //How to map this information into yarp structure?
820 natural_t total = 0;
821 for (int i = 0; i < CPU_STATE_MAX; ++i) {
822 total += cpu_load.cpu_ticks[i];
823 }
824
825 load.cpuLoad1 = 100.0 * cpu_load.cpu_ticks[CPU_STATE_USER] / total;
826 }
827#endif
828 return load;
829}
830
831
833{
834 // If not specified, get information for current process
835 if (pid == 0) {
836 pid = yarp::os::getpid();
837 }
838
840 info.pid = -1; // invalid
841 info.schedPolicy = -1;
842 info.schedPriority = -1;
843#if defined(__linux__)
844 FILE* file;
845 char cmdline[256] = {0};
846 char filename[256];
847 sprintf(filename, "/proc/%d/cmdline", pid);
848 file = fopen(filename, "r");
849 if (file != nullptr) {
850 char* p = fgets(cmdline, sizeof(cmdline) / sizeof(*cmdline), file);
851 fclose(file);
852 if (p != nullptr) {
853 while (*p != 0) {
854 p += strlen(p);
855 if (*(p + 1) != 0) {
856 *p = ' ';
857 }
858 p++;
859 }
860 info.pid = pid;
861 // split the cmdline to find the arguments
862 info.name = cmdline;
863 size_t index = info.name.find(' ');
864 if (index != std::string::npos) {
865 info.name = info.name.substr(0, index);
866 info.arguments = cmdline;
867 info.arguments = info.arguments.substr(index + 1);
868 }
869 }
870 }
871
872 // scheduling params
873 struct sched_param param;
874 if (sched_getparam(pid, &param) == 0) {
875 info.schedPriority = param.__sched_priority;
876 }
877 info.schedPolicy = sched_getscheduler(pid);
878
879#elif defined(_WIN32)
881 if (hnd) {
882 TCHAR filename[MAX_PATH];
883 if (GetModuleBaseName(hnd, 0, filename, MAX_PATH)) {
884 info.name = filename;
885 info.pid = pid;
886 }
888 }
889 // reterieving arguments
890 HRESULT hr = 0;
891 IWbemLocator* WbemLocator = nullptr;
892 IWbemServices* WbemServices = nullptr;
894
895 //initializate the Windows security
897 hr = CoInitializeSecurity(nullptr, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE, nullptr);
899 if (WbemLocator != nullptr) {
900 //connect to the WMI
901 BSTR val1 = SysAllocString(L"ROOT\\CimV2");
902 hr = WbemLocator->ConnectServer(val1, nullptr, nullptr, 0, 0, 0, 0, &WbemServices);
904 if (WbemServices != nullptr) {
905 //Run the WQL Query
906 BSTR val2 = SysAllocString(L"WQL");
907 BSTR val3 = SysAllocString(L"SELECT ProcessId, CommandLine FROM Win32_Process");
908 hr = WbemServices->ExecQuery(val2, val3, WBEM_FLAG_FORWARD_ONLY, nullptr, &EnumWbem);
911 // Iterate over the enumerator
912 if (EnumWbem != nullptr) {
913 IWbemClassObject* result = nullptr;
915
916 while ((hr = EnumWbem->Next(WBEM_INFINITE, 1, &result, &returnedCount)) == S_OK) {
919
920 // access the properties
921 hr = result->Get(L"ProcessId", 0, &ProcessId, 0, 0);
922 hr = result->Get(L"CommandLine", 0, &CommandLine, 0, 0);
923 if (!(CommandLine.vt == VT_NULL) && ProcessId.uintVal == (unsigned int)pid) {
924 // covert BSTR to std::string
925 int res = WideCharToMultiByte(CP_UTF8, 0, CommandLine.bstrVal, -1, nullptr, 0, nullptr, nullptr);
926 info.arguments.resize(res);
927 WideCharToMultiByte(CP_UTF8, 0, CommandLine.bstrVal, -1, &info.arguments[0], res, nullptr, nullptr);
928 size_t idx = info.arguments.find(' ');
929 if (idx == info.arguments.npos) {
930 info.arguments.clear();
931 } else {
932 info.arguments = info.arguments.substr(idx + 2); // it seems windows adds two spaces after the program name
933 }
934 info.pid = pid;
937 break;
938 }
939 result->Release();
940 } // end while
941
942 EnumWbem->Release();
943 } // end if EnumWbem
944
945 WbemServices->Release();
946 } // end if WbemServices
947
948 WbemLocator->Release();
949 } // end if WbemLocator
950
952#elif defined(__APPLE__)
954 size_t length = sizeof(procInfo);
955
956 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
957
958 if (!sysctl(mib, 4, &procInfo, &length, nullptr, 0)) {
959 info.name = procInfo.kp_proc.p_comm;
960 info.pid = procInfo.kp_proc.p_pid;
961
962 //Some info here: https://gist.github.com/nonowarn/770696
963 mib[1] = KERN_PROCARGS;
964 mib[2] = pid;
965 char* proc_argv;
966 size_t argv_len;
967 //getting length of execute string
968 int result = sysctl(mib, 3, nullptr, &argv_len, nullptr, 0);
969 if (result != 0) {
970 yCError(SYSTEMINFO, "sysctl: %d, %s", errno, strerror(errno));
971 return info;
972 }
973
974 //now getting the string
975 proc_argv = (char*)malloc(sizeof(char) * argv_len);
976 result = sysctl(mib, 3, proc_argv, &argv_len, nullptr, 0);
977 if (result != 0) {
978 yCError(SYSTEMINFO, "sysctl: %d, %s", errno, strerror(errno));
980 return info;
981 }
982
983 //looking for '\0', i.e. NULL char
984 //skip first string which is the executable
985 size_t index = 0;
986 while (index < argv_len && proc_argv[index] != '\0') {
987 index++;
988 }
989 index++;
990 //now we have to split the remaining string
991 //Note: this is not easy. We don't know the format
992 //See: http://lists.apple.com/archives/darwin-kernel/2012/Mar/msg00025.html
993 //for example, I get both arguments and environment variables
994
995 std::stringstream arguments;
996 while (index < argv_len) {
997 if (proc_argv[index] == '\0' && index != argv_len - 1) {
998 arguments << " ";
999 } else {
1000 arguments << proc_argv[index];
1001 }
1002 index++;
1003 }
1004
1005 free(proc_argv);
1006 info.arguments = arguments.str();
1007 }
1008
1009#endif
1010 return info;
1011}
A mini-server for performing network communication in the background.
void release(void *handle) override
Return control to YARP of an object previously taken control of with the acquire() method.
An interface for reading from a network connection.
An interface for writing to a network connection.
Holds the current cpu load information.
std::int32_t cpuLoadInstant
Holds the system memory information.
An abstraction for a periodic thread.
Holds the operating system information.
Holds the operating system process information.
Holds the processor information.
A class for storing options and configuration information.
Definition Property.h:32
A class for thread synchronization and mutual exclusion.
Definition Semaphore.h:25
Holds the system storage information.
bool write(const yarp::os::idl::WireWriter &writer) const override
bool read(yarp::os::idl::WireReader &reader) override
ProcessorInfoData processor
PlatformInfoData platform
static MemoryInfo getMemoryInfo()
getMemoryInfo
bool write(yarp::os::ConnectionWriter &connection) const override
write the SystemInfo structs using a ConnectionWriter.
static ProcessInfo getProcessInfo(int pid=0)
gets the operating system process information given by its PID.
static PlatformInfo getPlatformInfo()
getPlatformInfo
static UserInfo getUserInfo()
getUserInfo
bool read(yarp::os::ConnectionReader &connection) override
reads from a ConnectionReader and fill into the SystemInfo structs.
static LoadInfo getLoadInfo()
getLoadInfo
static StorageInfo getStorageInfo()
getStorageInfo
static ProcessorInfo getProcessorInfo()
getProcessorInfo
void updateSystemInfo()
updates the system information by calling the static methods to retrieve the latest data.
Holds the current user information.
#define yCError(component,...)
#define YARP_OS_LOG_COMPONENT(name, name_string)
An interface to the operating system, including Port based communication.
int getpid()
Portable wrapper for the getppid() function.
Definition Os.cpp:84
ShouldUseSystemClock
Definition Time.h:19
bool sum(yarp::sig::Image &OutImg, const yarp::sig::Image &InImg, bool colorkey_enable, int colorkey, bool alpha_enable, float alpha, size_t off_x, size_t off_y)
applies an image on the top over another image.