sysinfo/common/system.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
// Take a look at the license at the top of the repository in the LICENSE file.
use std::collections::{HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::path::Path;
use std::str::FromStr;
use crate::common::impl_get_set::impl_get_set;
use crate::common::DiskUsage;
use crate::{CpuInner, Gid, ProcessInner, SystemInner, Uid};
/// Structs containing system's information such as processes, memory and CPU.
///
/// ```
/// use sysinfo::System;
///
/// if sysinfo::IS_SUPPORTED_SYSTEM {
/// println!("System: {:?}", System::new_all());
/// } else {
/// println!("This OS isn't supported (yet?).");
/// }
/// ```
pub struct System {
pub(crate) inner: SystemInner,
}
impl Default for System {
fn default() -> System {
System::new()
}
}
impl System {
/// Creates a new [`System`] instance with nothing loaded.
///
/// Use one of the refresh methods (like [`refresh_all`]) to update its internal information.
///
/// [`System`]: crate::System
/// [`refresh_all`]: #method.refresh_all
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new();
/// ```
pub fn new() -> Self {
Self::new_with_specifics(RefreshKind::nothing())
}
/// Creates a new [`System`] instance with everything loaded.
///
/// It is an equivalent of [`System::new_with_specifics`]`(`[`RefreshKind::everything`]`())`.
///
/// [`System`]: crate::System
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// ```
pub fn new_all() -> Self {
Self::new_with_specifics(RefreshKind::everything())
}
/// Creates a new [`System`] instance and refresh the data corresponding to the
/// given [`RefreshKind`].
///
/// [`System`]: crate::System
///
/// ```
/// use sysinfo::{ProcessRefreshKind, RefreshKind, System};
///
/// // We want to only refresh processes.
/// let mut system = System::new_with_specifics(
/// RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
/// );
///
/// # if sysinfo::IS_SUPPORTED_SYSTEM && !cfg!(feature = "apple-sandbox") {
/// assert!(!system.processes().is_empty());
/// # }
/// ```
pub fn new_with_specifics(refreshes: RefreshKind) -> Self {
let mut s = Self {
inner: SystemInner::new(),
};
s.refresh_specifics(refreshes);
s
}
/// Refreshes according to the given [`RefreshKind`]. It calls the corresponding
/// "refresh_" methods.
///
/// ```
/// use sysinfo::{ProcessRefreshKind, RefreshKind, System};
///
/// let mut s = System::new_all();
///
/// // Let's just update processes:
/// s.refresh_specifics(
/// RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
/// );
/// ```
pub fn refresh_specifics(&mut self, refreshes: RefreshKind) {
if let Some(kind) = refreshes.memory() {
self.refresh_memory_specifics(kind);
}
if let Some(kind) = refreshes.cpu() {
self.refresh_cpu_specifics(kind);
}
if let Some(kind) = refreshes.processes() {
self.refresh_processes_specifics(ProcessesToUpdate::All, false, kind);
}
}
/// Refreshes all system and processes information.
///
/// It is the same as calling `system.refresh_specifics(RefreshKind::everything())`.
///
/// Don't forget to take a look at [`ProcessRefreshKind::everything`] method to see what it
/// will update for processes more in details.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new();
/// s.refresh_all();
/// ```
pub fn refresh_all(&mut self) {
self.refresh_specifics(RefreshKind::everything());
}
/// Refreshes RAM and SWAP usage.
///
/// It is the same as calling `system.refresh_memory_specifics(MemoryRefreshKind::everything())`.
///
/// If you don't want to refresh both, take a look at [`System::refresh_memory_specifics`].
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new();
/// s.refresh_memory();
/// ```
pub fn refresh_memory(&mut self) {
self.refresh_memory_specifics(MemoryRefreshKind::everything())
}
/// Refreshes system memory specific information.
///
/// ```no_run
/// use sysinfo::{MemoryRefreshKind, System};
///
/// let mut s = System::new();
/// s.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
/// ```
pub fn refresh_memory_specifics(&mut self, refresh_kind: MemoryRefreshKind) {
self.inner.refresh_memory_specifics(refresh_kind)
}
/// Refreshes CPUs usage.
///
/// ⚠️ Please note that the result will very likely be inaccurate at the first call.
/// You need to call this method at least twice (with a bit of time between each call, like
/// 200 ms, take a look at [`MINIMUM_CPU_UPDATE_INTERVAL`] for more information)
/// to get accurate value as it uses previous results to compute the next value.
///
/// Calling this method is the same as calling
/// `system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_cpu_usage())`.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new_all();
/// // Wait a bit because CPU usage is based on diff.
/// std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
/// // Refresh CPUs again.
/// s.refresh_cpu_usage();
/// ```
///
/// [`MINIMUM_CPU_UPDATE_INTERVAL`]: crate::MINIMUM_CPU_UPDATE_INTERVAL
pub fn refresh_cpu_usage(&mut self) {
self.refresh_cpu_specifics(CpuRefreshKind::nothing().with_cpu_usage())
}
/// Refreshes CPUs frequency information.
///
/// Calling this method is the same as calling
/// `system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_frequency())`.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new_all();
/// s.refresh_cpu_frequency();
/// ```
pub fn refresh_cpu_frequency(&mut self) {
self.refresh_cpu_specifics(CpuRefreshKind::nothing().with_frequency())
}
/// Refreshes the list of CPU.
///
/// Normally, this should almost never be needed as it's pretty rare for a computer
/// to add a CPU while running, but it's possible on some computers which shutdown
/// CPU if the load is low enough.
///
/// The `refresh_kind` argument tells what information you want to be retrieved
/// for each CPU.
///
/// ```no_run
/// use sysinfo::{CpuRefreshKind, System};
///
/// let mut s = System::new_all();
/// // We already have the list of CPU filled, but we want to recompute it
/// // in case new CPUs were added.
/// s.refresh_cpu_list(CpuRefreshKind::everything());
/// ```
pub fn refresh_cpu_list(&mut self, refresh_kind: CpuRefreshKind) {
self.inner.refresh_cpu_list(refresh_kind);
}
/// Refreshes all information related to CPUs information.
///
/// If you only want the CPU usage, use [`System::refresh_cpu_usage`] instead.
///
/// ⚠️ Please note that the result will be inaccurate at the first call.
/// You need to call this method at least twice (with a bit of time between each call, like
/// 200 ms, take a look at [`MINIMUM_CPU_UPDATE_INTERVAL`] for more information)
/// to get accurate value as it uses previous results to compute the next value.
///
/// Calling this method is the same as calling
/// `system.refresh_cpu_specifics(CpuRefreshKind::everything())`.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new_all();
/// s.refresh_cpu_all();
/// ```
///
/// [`MINIMUM_CPU_UPDATE_INTERVAL`]: crate::MINIMUM_CPU_UPDATE_INTERVAL
pub fn refresh_cpu_all(&mut self) {
self.refresh_cpu_specifics(CpuRefreshKind::everything())
}
/// Refreshes CPUs specific information.
///
/// ```no_run
/// use sysinfo::{System, CpuRefreshKind};
///
/// let mut s = System::new_all();
/// s.refresh_cpu_specifics(CpuRefreshKind::everything());
/// ```
pub fn refresh_cpu_specifics(&mut self, refresh_kind: CpuRefreshKind) {
self.inner.refresh_cpu_specifics(refresh_kind)
}
/// Gets all processes and updates their information.
///
/// It does the same as:
///
/// ```no_run
/// # use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System, UpdateKind};
/// # let mut system = System::new();
/// system.refresh_processes_specifics(
/// ProcessesToUpdate::All,
/// true,
/// ProcessRefreshKind::nothing()
/// .with_memory()
/// .with_cpu()
/// .with_disk_usage()
/// .with_exe(UpdateKind::OnlyIfNotSet),
/// );
/// ```
///
/// ⚠️ `remove_dead_processes` works as follows: if an updated process is dead, then it is
/// removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed
/// since 7 is not part of the update.
///
/// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour
/// by using [`set_open_files_limit`][crate::set_open_files_limit].
///
/// Example:
///
/// ```no_run
/// use sysinfo::{ProcessesToUpdate, System};
///
/// let mut s = System::new_all();
/// s.refresh_processes(ProcessesToUpdate::All, true);
/// ```
pub fn refresh_processes(
&mut self,
processes_to_update: ProcessesToUpdate<'_>,
remove_dead_processes: bool,
) -> usize {
self.refresh_processes_specifics(
processes_to_update,
remove_dead_processes,
ProcessRefreshKind::nothing()
.with_memory()
.with_cpu()
.with_disk_usage()
.with_exe(UpdateKind::OnlyIfNotSet),
)
}
/// Gets all processes and updates the specified information.
///
/// Returns the number of updated processes.
///
/// ⚠️ `remove_dead_processes` works as follows: if an updated process is dead, then it is
/// removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed
/// since 7 is not part of the update.
///
/// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour
/// by using [`set_open_files_limit`][crate::set_open_files_limit].
///
/// ```no_run
/// use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System};
///
/// let mut s = System::new_all();
/// s.refresh_processes_specifics(
/// ProcessesToUpdate::All,
/// true,
/// ProcessRefreshKind::everything(),
/// );
/// ```
pub fn refresh_processes_specifics(
&mut self,
processes_to_update: ProcessesToUpdate<'_>,
remove_dead_processes: bool,
refresh_kind: ProcessRefreshKind,
) -> usize {
fn update_and_remove(pid: &Pid, processes: &mut HashMap<Pid, Process>) {
let updated = if let Some(proc) = processes.get_mut(pid) {
proc.inner.switch_updated()
} else {
return;
};
if !updated {
processes.remove(pid);
}
}
fn update(pid: &Pid, processes: &mut HashMap<Pid, Process>) {
if let Some(proc) = processes.get_mut(pid) {
proc.inner.switch_updated();
}
}
let nb_updated = self
.inner
.refresh_processes_specifics(processes_to_update, refresh_kind);
let processes = self.inner.processes_mut();
match processes_to_update {
ProcessesToUpdate::All => {
if remove_dead_processes {
processes.retain(|_, v| v.inner.switch_updated());
} else {
for proc in processes.values_mut() {
proc.inner.switch_updated();
}
}
}
ProcessesToUpdate::Some(pids) => {
let call = if remove_dead_processes {
update_and_remove
} else {
update
};
for pid in pids {
call(pid, processes);
}
}
}
nb_updated
}
/// Returns the process list.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// for (pid, process) in s.processes() {
/// println!("{} {:?}", pid, process.name());
/// }
/// ```
pub fn processes(&self) -> &HashMap<Pid, Process> {
self.inner.processes()
}
/// Returns the process corresponding to the given `pid` or `None` if no such process exists.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.name());
/// }
/// ```
pub fn process(&self, pid: Pid) -> Option<&Process> {
self.inner.process(pid)
}
/// Returns an iterator of process containing the given `name`.
///
/// If you want only the processes with exactly the given `name`, take a look at
/// [`System::processes_by_exact_name`].
///
/// **⚠️ Important ⚠️**
///
/// On **Linux**, there are two things to know about processes' name:
/// 1. It is limited to 15 characters.
/// 2. It is not always the exe name.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// for process in s.processes_by_name("htop".as_ref()) {
/// println!("{} {:?}", process.pid(), process.name());
/// }
/// ```
pub fn processes_by_name<'a: 'b, 'b>(
&'a self,
name: &'b OsStr,
) -> impl Iterator<Item = &'a Process> + 'b {
let finder = memchr::memmem::Finder::new(name.as_encoded_bytes());
self.processes()
.values()
.filter(move |val: &&Process| finder.find(val.name().as_encoded_bytes()).is_some())
}
/// Returns an iterator of processes with exactly the given `name`.
///
/// If you instead want the processes containing `name`, take a look at
/// [`System::processes_by_name`].
///
/// **⚠️ Important ⚠️**
///
/// On **Linux**, there are two things to know about processes' name:
/// 1. It is limited to 15 characters.
/// 2. It is not always the exe name.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// for process in s.processes_by_exact_name("htop".as_ref()) {
/// println!("{} {:?}", process.pid(), process.name());
/// }
/// ```
pub fn processes_by_exact_name<'a: 'b, 'b>(
&'a self,
name: &'b OsStr,
) -> impl Iterator<Item = &'a Process> + 'b {
self.processes()
.values()
.filter(move |val: &&Process| val.name() == name)
}
/// Returns "global" CPUs usage (aka the addition of all the CPUs).
///
/// To have up-to-date information, you need to call [`System::refresh_cpu_specifics`] or
/// [`System::refresh_specifics`] with `cpu` enabled.
///
/// ```no_run
/// use sysinfo::{CpuRefreshKind, RefreshKind, System};
///
/// let mut s = System::new_with_specifics(
/// RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
/// );
/// // Wait a bit because CPU usage is based on diff.
/// std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
/// // Refresh CPUs again to get actual value.
/// s.refresh_cpu_usage();
/// println!("{}%", s.global_cpu_usage());
/// ```
pub fn global_cpu_usage(&self) -> f32 {
self.inner.global_cpu_usage()
}
/// Returns the list of the CPUs.
///
/// By default, the list of CPUs is empty until you call [`System::refresh_cpu_specifics`] or
/// [`System::refresh_specifics`] with `cpu` enabled.
///
/// ```no_run
/// use sysinfo::{CpuRefreshKind, RefreshKind, System};
///
/// let mut s = System::new_with_specifics(
/// RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
/// );
/// // Wait a bit because CPU usage is based on diff.
/// std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
/// // Refresh CPUs again to get actual value.
/// s.refresh_cpu_usage();
/// for cpu in s.cpus() {
/// println!("{}%", cpu.cpu_usage());
/// }
/// ```
pub fn cpus(&self) -> &[Cpu] {
self.inner.cpus()
}
/// Returns the number of physical cores on the CPU or `None` if it couldn't get it.
///
/// In case there are multiple CPUs, it will combine the physical core count of all the CPUs.
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new();
/// println!("{:?}", s.physical_core_count());
/// ```
pub fn physical_core_count(&self) -> Option<usize> {
self.inner.physical_core_count()
}
/// Returns the RAM size in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.total_memory());
/// ```
///
/// On Linux, if you want to see this information with the limit of your cgroup, take a look
/// at [`cgroup_limits`](System::cgroup_limits).
pub fn total_memory(&self) -> u64 {
self.inner.total_memory()
}
/// Returns the amount of free RAM in bytes.
///
/// Generally, "free" memory refers to unallocated memory whereas "available" memory refers to
/// memory that is available for (re)use.
///
/// Side note: Windows doesn't report "free" memory so this method returns the same value
/// as [`available_memory`](System::available_memory).
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.free_memory());
/// ```
pub fn free_memory(&self) -> u64 {
self.inner.free_memory()
}
/// Returns the amount of available RAM in bytes.
///
/// Generally, "free" memory refers to unallocated memory whereas "available" memory refers to
/// memory that is available for (re)use.
///
/// ⚠️ Windows and FreeBSD don't report "available" memory so [`System::free_memory`]
/// returns the same value as this method.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.available_memory());
/// ```
pub fn available_memory(&self) -> u64 {
self.inner.available_memory()
}
/// Returns the amount of used RAM in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.used_memory());
/// ```
pub fn used_memory(&self) -> u64 {
self.inner.used_memory()
}
/// Returns the SWAP size in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.total_swap());
/// ```
pub fn total_swap(&self) -> u64 {
self.inner.total_swap()
}
/// Returns the amount of free SWAP in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.free_swap());
/// ```
pub fn free_swap(&self) -> u64 {
self.inner.free_swap()
}
/// Returns the amount of used SWAP in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.used_swap());
/// ```
pub fn used_swap(&self) -> u64 {
self.inner.used_swap()
}
/// Retrieves the limits for the current cgroup (if any), otherwise it returns `None`.
///
/// This information is computed every time the method is called.
///
/// ⚠️ You need to have run [`refresh_memory`](System::refresh_memory) at least once before
/// calling this method.
///
/// ⚠️ This method is only implemented for Linux. It always returns `None` for all other
/// systems.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("limits: {:?}", s.cgroup_limits());
/// ```
pub fn cgroup_limits(&self) -> Option<CGroupLimits> {
self.inner.cgroup_limits()
}
/// Returns system uptime (in seconds).
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("System running since {} seconds", System::uptime());
/// ```
pub fn uptime() -> u64 {
SystemInner::uptime()
}
/// Returns the time (in seconds) when the system booted since UNIX epoch.
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("System booted at {} seconds", System::boot_time());
/// ```
pub fn boot_time() -> u64 {
SystemInner::boot_time()
}
/// Returns the system load average value.
///
/// **Important**: this information is computed every time this function is called.
///
/// ⚠️ This is currently not working on **Windows**.
///
/// ```no_run
/// use sysinfo::System;
///
/// let load_avg = System::load_average();
/// println!(
/// "one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
/// load_avg.one,
/// load_avg.five,
/// load_avg.fifteen,
/// );
/// ```
pub fn load_average() -> LoadAvg {
SystemInner::load_average()
}
/// Returns the system name.
///
/// | example platform | value of `System::name()` |
/// |---|---|
/// | linux laptop | "Ubuntu" |
/// | android phone | "Pixel 9 Pro" |
/// | apple laptop | "Darwin" |
/// | windows server | "Windows" |
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("OS: {:?}", System::name());
/// ```
pub fn name() -> Option<String> {
SystemInner::name()
}
/// Returns the system's kernel version.
///
/// | example platform | value of `System::kernel_version()` |
/// |---|---|
/// | linux laptop | "6.8.0-48-generic" |
/// | android phone | "6.1.84-android14-11" |
/// | apple laptop | "24.1.0" |
/// | windows server | "20348" |
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("kernel version: {:?}", System::kernel_version());
/// ```
pub fn kernel_version() -> Option<String> {
SystemInner::kernel_version()
}
/// Returns the system version (e.g. for macOS this will return 15.1 rather than the kernel
/// version).
///
/// | example platform | value of `System::os_version()` |
/// |---|---|
/// | linux laptop | "24.04" |
/// | android phone | "15" |
/// | apple laptop | "15.1.1" |
/// | windows server | "10 (20348)" |
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("OS version: {:?}", System::os_version());
/// ```
pub fn os_version() -> Option<String> {
SystemInner::os_version()
}
/// Returns the system long os version.
///
/// | example platform | value of `System::long_os_version()` |
/// |---|---|
/// | linux laptop | "Linux (Ubuntu 24.04)" |
/// | android phone | "Android 15 on Pixel 9 Pro" |
/// | apple laptop | "macOS 15.1.1 Sequoia" |
/// | windows server | "Windows Server 2022 Datacenter" |
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("Long OS Version: {:?}", System::long_os_version());
/// ```
pub fn long_os_version() -> Option<String> {
SystemInner::long_os_version()
}
/// Returns the distribution id as defined by os-release,
/// or [`std::env::consts::OS`].
///
/// See also
/// - <https://www.freedesktop.org/software/systemd/man/os-release.html#ID=>
/// - <https://doc.rust-lang.org/std/env/consts/constant.OS.html>
///
/// | example platform | value of `System::distribution_id()` |
/// |---|---|
/// | linux laptop | "ubuntu" |
/// | android phone | "android" |
/// | apple laptop | "macos" |
/// | windows server | "windows" |
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("Distribution ID: {:?}", System::distribution_id());
/// ```
pub fn distribution_id() -> String {
SystemInner::distribution_id()
}
/// Returns the system hostname based off DNS.
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("Hostname: {:?}", System::host_name());
/// ```
pub fn host_name() -> Option<String> {
SystemInner::host_name()
}
/// Returns the CPU architecture (eg. x86, amd64, aarch64, ...).
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("CPU Architecture: {:?}", System::cpu_arch());
/// ```
pub fn cpu_arch() -> String {
SystemInner::cpu_arch().unwrap_or_else(|| std::env::consts::ARCH.to_owned())
}
}
/// A struct representing system load average value.
///
/// It is returned by [`System::load_average`][crate::System::load_average].
///
/// ```no_run
/// use sysinfo::System;
///
/// let load_avg = System::load_average();
/// println!(
/// "one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
/// load_avg.one,
/// load_avg.five,
/// load_avg.fifteen,
/// );
/// ```
#[repr(C)]
#[derive(Default, Debug, Clone)]
pub struct LoadAvg {
/// Average load within one minute.
pub one: f64,
/// Average load within five minutes.
pub five: f64,
/// Average load within fifteen minutes.
pub fifteen: f64,
}
/// An enum representing signals on UNIX-like systems.
///
/// On non-unix systems, this enum is mostly useless and is only there to keep coherency between
/// the different OSes.
///
/// If you want the list of the supported signals on the current system, use
/// [`SUPPORTED_SIGNALS`][crate::SUPPORTED_SIGNALS].
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Debug)]
pub enum Signal {
/// Hangup detected on controlling terminal or death of controlling process.
Hangup,
/// Interrupt from keyboard.
Interrupt,
/// Quit from keyboard.
Quit,
/// Illegal instruction.
Illegal,
/// Trace/breakpoint trap.
Trap,
/// Abort signal from C abort function.
Abort,
/// IOT trap. A synonym for SIGABRT.
IOT,
/// Bus error (bad memory access).
Bus,
/// Floating point exception.
FloatingPointException,
/// Kill signal.
Kill,
/// User-defined signal 1.
User1,
/// Invalid memory reference.
Segv,
/// User-defined signal 2.
User2,
/// Broken pipe: write to pipe with no readers.
Pipe,
/// Timer signal from C alarm function.
Alarm,
/// Termination signal.
Term,
/// Child stopped or terminated.
Child,
/// Continue if stopped.
Continue,
/// Stop process.
Stop,
/// Stop typed at terminal.
TSTP,
/// Terminal input for background process.
TTIN,
/// Terminal output for background process.
TTOU,
/// Urgent condition on socket.
Urgent,
/// CPU time limit exceeded.
XCPU,
/// File size limit exceeded.
XFSZ,
/// Virtual alarm clock.
VirtualAlarm,
/// Profiling time expired.
Profiling,
/// Windows resize signal.
Winch,
/// I/O now possible.
IO,
/// Pollable event (Sys V). Synonym for IO
Poll,
/// Power failure (System V).
///
/// Doesn't exist on apple systems so will be ignored.
Power,
/// Bad argument to routine (SVr4).
Sys,
}
impl std::fmt::Display for Signal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match *self {
Self::Hangup => "Hangup",
Self::Interrupt => "Interrupt",
Self::Quit => "Quit",
Self::Illegal => "Illegal",
Self::Trap => "Trap",
Self::Abort => "Abort",
Self::IOT => "IOT",
Self::Bus => "Bus",
Self::FloatingPointException => "FloatingPointException",
Self::Kill => "Kill",
Self::User1 => "User1",
Self::Segv => "Segv",
Self::User2 => "User2",
Self::Pipe => "Pipe",
Self::Alarm => "Alarm",
Self::Term => "Term",
Self::Child => "Child",
Self::Continue => "Continue",
Self::Stop => "Stop",
Self::TSTP => "TSTP",
Self::TTIN => "TTIN",
Self::TTOU => "TTOU",
Self::Urgent => "Urgent",
Self::XCPU => "XCPU",
Self::XFSZ => "XFSZ",
Self::VirtualAlarm => "VirtualAlarm",
Self::Profiling => "Profiling",
Self::Winch => "Winch",
Self::IO => "IO",
Self::Poll => "Poll",
Self::Power => "Power",
Self::Sys => "Sys",
};
f.write_str(s)
}
}
/// Contains memory limits for the current process.
#[derive(Default, Debug, Clone)]
pub struct CGroupLimits {
/// Total memory (in bytes) for the current cgroup.
pub total_memory: u64,
/// Free memory (in bytes) for the current cgroup.
pub free_memory: u64,
/// Free swap (in bytes) for the current cgroup.
pub free_swap: u64,
/// Resident Set Size (RSS) (in bytes) for the current cgroup.
pub rss: u64,
}
/// Enum describing the different status of a process.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProcessStatus {
/// ## Linux
///
/// Idle kernel thread.
///
/// ## macOs/FreeBSD
///
/// Process being created by fork.
///
/// ## Other OS
///
/// Not available.
Idle,
/// Running.
Run,
/// ## Linux
///
/// Sleeping in an interruptible waiting.
///
/// ## macOS/FreeBSD
///
/// Sleeping on an address.
///
/// ## Other OS
///
/// Not available.
Sleep,
/// ## Linux
///
/// Stopped (on a signal) or (before Linux 2.6.33) trace stopped.
///
/// ## macOS/FreeBSD
///
/// Process debugging or suspension.
///
/// ## Other OS
///
/// Not available.
Stop,
/// ## Linux/FreeBSD/macOS
///
/// Zombie process. Terminated but not reaped by its parent.
///
/// ## Other OS
///
/// Not available.
Zombie,
/// ## Linux
///
/// Tracing stop (Linux 2.6.33 onward). Stopped by debugger during the tracing.
///
/// ## Other OS
///
/// Not available.
Tracing,
/// ## Linux
///
/// Dead/uninterruptible sleep (usually IO).
///
/// ## FreeBSD
///
/// A process should never end up in this state.
///
/// ## Other OS
///
/// Not available.
Dead,
/// ## Linux
///
/// Wakekill (Linux 2.6.33 to 3.13 only).
///
/// ## Other OS
///
/// Not available.
Wakekill,
/// ## Linux
///
/// Waking (Linux 2.6.33 to 3.13 only).
///
/// ## Other OS
///
/// Not available.
Waking,
/// ## Linux
///
/// Parked (Linux 3.9 to 3.13 only).
///
/// ## macOS
///
/// Halted at a clean point.
///
/// ## Other OS
///
/// Not available.
Parked,
/// ## FreeBSD
///
/// Blocked on a lock.
///
/// ## Other OS
///
/// Not available.
LockBlocked,
/// ## Linux
///
/// Waiting in uninterruptible disk sleep.
///
/// ## Other OS
///
/// Not available.
UninterruptibleDiskSleep,
/// Unknown.
Unknown(u32),
}
/// Enum describing the different kind of threads.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ThreadKind {
/// Kernel thread.
Kernel,
/// User thread.
Userland,
}
/// Struct containing information of a process.
///
/// ## iOS
///
/// This information cannot be retrieved on iOS due to sandboxing.
///
/// ## Apple app store
///
/// If you are building a macOS Apple app store, it won't be able
/// to retrieve this information.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.name());
/// }
/// ```
pub struct Process {
pub(crate) inner: ProcessInner,
}
impl Process {
/// Sends [`Signal::Kill`] to the process (which is the only signal supported on all supported
/// platforms by this crate).
///
/// Returns `true` if the signal was sent successfully. If you want to wait for this process
/// to end, you can use [`Process::wait`].
///
/// ⚠️ Even if this function returns `true`, it doesn't necessarily mean that the process will
/// be killed. It just means that the signal was sent successfully.
///
/// ⚠️ Please note that some processes might not be "killable", like if they run with higher
/// levels than the current process for example.
///
/// If you want to use another signal, take a look at [`Process::kill_with`].
///
/// To get the list of the supported signals on this system, use
/// [`SUPPORTED_SIGNALS`][crate::SUPPORTED_SIGNALS].
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// process.kill();
/// }
/// ```
pub fn kill(&self) -> bool {
self.kill_with(Signal::Kill).unwrap_or(false)
}
/// Sends the given `signal` to the process. If the signal doesn't exist on this platform,
/// it'll do nothing and will return `None`. Otherwise it'll return `Some(bool)`. The boolean
/// value will depend on whether or not the signal was sent successfully.
///
/// If you just want to kill the process, use [`Process::kill`] directly. If you want to wait
/// for this process to end, you can use [`Process::wait`].
///
/// ⚠️ Please note that some processes might not be "killable", like if they run with higher
/// levels than the current process for example.
///
/// To get the list of the supported signals on this system, use
/// [`SUPPORTED_SIGNALS`][crate::SUPPORTED_SIGNALS].
///
/// ```no_run
/// use sysinfo::{Pid, Signal, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// if process.kill_with(Signal::Kill).is_none() {
/// println!("This signal isn't supported on this platform");
/// }
/// }
/// ```
pub fn kill_with(&self, signal: Signal) -> Option<bool> {
self.inner.kill_with(signal)
}
/// Wait for process termination.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let mut s = System::new_all();
///
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("Waiting for pid 1337");
/// process.wait();
/// println!("Pid 1337 exited");
/// }
/// ```
pub fn wait(&self) {
self.inner.wait()
}
/// Returns the name of the process.
///
/// **⚠️ Important ⚠️**
///
/// On **Linux**, there are two things to know about processes' name:
/// 1. It is limited to 15 characters.
/// 2. It is not always the exe name.
///
/// If you are looking for a specific process, unless you know what you are
/// doing, in most cases it's better to use [`Process::exe`] instead (which
/// can be empty sometimes!).
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.name());
/// }
/// ```
pub fn name(&self) -> &OsStr {
self.inner.name()
}
/// Returns the command line.
///
/// **⚠️ Important ⚠️**
///
/// On **Windows**, you might need to use `administrator` privileges when running your program
/// to have access to this information.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.cmd());
/// }
/// ```
pub fn cmd(&self) -> &[OsString] {
self.inner.cmd()
}
/// Returns the path to the process.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.exe());
/// }
/// ```
///
/// ### Implementation notes
///
/// On Linux, this method will return an empty path if there
/// was an error trying to read `/proc/<pid>/exe`. This can
/// happen, for example, if the permission levels or UID namespaces
/// between the caller and target processes are different.
///
/// It is also the case that `cmd[0]` is _not_ usually a correct
/// replacement for this.
/// A process [may change its `cmd[0]` value](https://man7.org/linux/man-pages/man5/proc.5.html)
/// freely, making this an untrustworthy source of information.
pub fn exe(&self) -> Option<&Path> {
self.inner.exe()
}
/// Returns the PID of the process.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{}", process.pid());
/// }
/// ```
pub fn pid(&self) -> Pid {
self.inner.pid()
}
/// Returns the environment variables of the process.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.environ());
/// }
/// ```
pub fn environ(&self) -> &[OsString] {
self.inner.environ()
}
/// Returns the current working directory.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.cwd());
/// }
/// ```
pub fn cwd(&self) -> Option<&Path> {
self.inner.cwd()
}
/// Returns the path of the root directory.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.root());
/// }
/// ```
pub fn root(&self) -> Option<&Path> {
self.inner.root()
}
/// Returns the memory usage (in bytes).
///
/// This method returns the [size of the resident set], that is, the amount of memory that the
/// process allocated and which is currently mapped in physical RAM. It does not include memory
/// that is swapped out, or, in some operating systems, that has been allocated but never used.
///
/// Thus, it represents exactly the amount of physical RAM that the process is using at the
/// present time, but it might not be a good indicator of the total memory that the process will
/// be using over its lifetime. For that purpose, you can try and use
/// [`virtual_memory`](Process::virtual_memory).
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{} bytes", process.memory());
/// }
/// ```
///
/// [size of the resident set]: https://en.wikipedia.org/wiki/Resident_set_size
pub fn memory(&self) -> u64 {
self.inner.memory()
}
/// Returns the virtual memory usage (in bytes).
///
/// This method returns the [size of virtual memory], that is, the amount of memory that the
/// process can access, whether it is currently mapped in physical RAM or not. It includes
/// physical RAM, allocated but not used regions, swapped-out regions, and even memory
/// associated with [memory-mapped files](https://en.wikipedia.org/wiki/Memory-mapped_file).
///
/// This value has limitations though. Depending on the operating system and type of process,
/// this value might be a good indicator of the total memory that the process will be using over
/// its lifetime. However, for example, in the version 14 of macOS this value is in the order of
/// the hundreds of gigabytes for every process, and thus not very informative. Moreover, if a
/// process maps into memory a very large file, this value will increase accordingly, even if
/// the process is not actively using the memory.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{} bytes", process.virtual_memory());
/// }
/// ```
///
/// [size of virtual memory]: https://en.wikipedia.org/wiki/Virtual_memory
pub fn virtual_memory(&self) -> u64 {
self.inner.virtual_memory()
}
/// Returns the parent PID.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.parent());
/// }
/// ```
pub fn parent(&self) -> Option<Pid> {
self.inner.parent()
}
/// Returns the status of the process.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.status());
/// }
/// ```
pub fn status(&self) -> ProcessStatus {
self.inner.status()
}
/// Returns the time where the process was started (in seconds) from epoch.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("Started at {} seconds", process.start_time());
/// }
/// ```
pub fn start_time(&self) -> u64 {
self.inner.start_time()
}
/// Returns for how much time the process has been running (in seconds).
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("Running since {} seconds", process.run_time());
/// }
/// ```
pub fn run_time(&self) -> u64 {
self.inner.run_time()
}
/// Returns the total CPU usage (in %). Notice that it might be bigger than
/// 100 if run on a multi-core machine.
///
/// If you want a value between 0% and 100%, divide the returned value by
/// the number of CPUs.
///
/// ⚠️ To start to have accurate CPU usage, a process needs to be refreshed
/// **twice** because CPU usage computation is based on time diff (process
/// time on a given time period divided by total system time on the same
/// time period).
///
/// ⚠️ If you want accurate CPU usage number, better leave a bit of time
/// between two calls of this method (take a look at
/// [`MINIMUM_CPU_UPDATE_INTERVAL`][crate::MINIMUM_CPU_UPDATE_INTERVAL] for
/// more information).
///
/// ```no_run
/// use sysinfo::{Pid, ProcessesToUpdate, ProcessRefreshKind, System};
///
/// let mut s = System::new_all();
/// // Wait a bit because CPU usage is based on diff.
/// std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
/// // Refresh CPU usage to get actual value.
/// s.refresh_processes_specifics(
/// ProcessesToUpdate::All,
/// true,
/// ProcessRefreshKind::nothing().with_cpu()
/// );
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{}%", process.cpu_usage());
/// }
/// ```
pub fn cpu_usage(&self) -> f32 {
self.inner.cpu_usage()
}
/// Returns number of bytes read and written to disk.
///
/// ⚠️ On Windows, this method actually returns **ALL** I/O read and
/// written bytes.
///
/// ⚠️ Files might be cached in memory by your OS, meaning that reading/writing them might not
/// increase the `read_bytes`/`written_bytes` values. You can find more information about it
/// in the `proc_pid_io` manual (`man proc_pid_io` on unix platforms).
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// let disk_usage = process.disk_usage();
/// println!("read bytes : new/total => {}/{}",
/// disk_usage.read_bytes,
/// disk_usage.total_read_bytes,
/// );
/// println!("written bytes: new/total => {}/{}",
/// disk_usage.written_bytes,
/// disk_usage.total_written_bytes,
/// );
/// }
/// ```
pub fn disk_usage(&self) -> DiskUsage {
self.inner.disk_usage()
}
/// Returns the ID of the owner user of this process or `None` if this
/// information couldn't be retrieved. If you want to get the [`User`] from
/// it, take a look at [`Users::get_user_by_id`].
///
/// [`User`]: crate::User
/// [`Users::get_user_by_id`]: crate::Users::get_user_by_id
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let mut s = System::new_all();
///
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("User id for process 1337: {:?}", process.user_id());
/// }
/// ```
pub fn user_id(&self) -> Option<&Uid> {
self.inner.user_id()
}
/// Returns the user ID of the effective owner of this process or `None` if
/// this information couldn't be retrieved. If you want to get the [`User`]
/// from it, take a look at [`Users::get_user_by_id`].
///
/// If you run something with `sudo`, the real user ID of the launched
/// process will be the ID of the user you are logged in as but effective
/// user ID will be `0` (i-e root).
///
/// ⚠️ It always returns `None` on Windows.
///
/// [`User`]: crate::User
/// [`Users::get_user_by_id`]: crate::Users::get_user_by_id
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let mut s = System::new_all();
///
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("User id for process 1337: {:?}", process.effective_user_id());
/// }
/// ```
pub fn effective_user_id(&self) -> Option<&Uid> {
self.inner.effective_user_id()
}
/// Returns the process group ID of the process.
///
/// ⚠️ It always returns `None` on Windows.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let mut s = System::new_all();
///
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("Group ID for process 1337: {:?}", process.group_id());
/// }
/// ```
pub fn group_id(&self) -> Option<Gid> {
self.inner.group_id()
}
/// Returns the effective group ID of the process.
///
/// If you run something with `sudo`, the real group ID of the launched
/// process will be the primary group ID you are logged in as but effective
/// group ID will be `0` (i-e root).
///
/// ⚠️ It always returns `None` on Windows.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let mut s = System::new_all();
///
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("User id for process 1337: {:?}", process.effective_group_id());
/// }
/// ```
pub fn effective_group_id(&self) -> Option<Gid> {
self.inner.effective_group_id()
}
/// Returns the session ID for the current process or `None` if it couldn't
/// be retrieved.
///
/// ⚠️ This information is computed every time this method is called.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let mut s = System::new_all();
///
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("Session ID for process 1337: {:?}", process.session_id());
/// }
/// ```
pub fn session_id(&self) -> Option<Pid> {
self.inner.session_id()
}
/// Tasks run by this process. If there are none, returns `None`.
///
/// ⚠️ This method always returns `None` on other platforms than Linux.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let mut s = System::new_all();
///
/// if let Some(process) = s.process(Pid::from(1337)) {
/// if let Some(tasks) = process.tasks() {
/// println!("Listing tasks for process {:?}", process.pid());
/// for task_pid in tasks {
/// if let Some(task) = s.process(*task_pid) {
/// println!("Task {:?}: {:?}", task.pid(), task.name());
/// }
/// }
/// }
/// }
/// ```
pub fn tasks(&self) -> Option<&HashSet<Pid>> {
cfg_if! {
if #[cfg(all(
any(target_os = "linux", target_os = "android"),
not(feature = "unknown-ci")
))] {
self.inner.tasks.as_ref()
} else {
None
}
}
}
/// If the process is a thread, it'll return `Some` with the kind of thread it is. Returns
/// `None` otherwise.
///
/// ⚠️ This method always returns `None` on other platforms than Linux.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
///
/// for (_, process) in s.processes() {
/// if let Some(thread_kind) = process.thread_kind() {
/// println!("Process {:?} is a {thread_kind:?} thread", process.pid());
/// }
/// }
/// ```
pub fn thread_kind(&self) -> Option<ThreadKind> {
cfg_if! {
if #[cfg(all(
any(target_os = "linux", target_os = "android"),
not(feature = "unknown-ci")
))] {
self.inner.thread_kind()
} else {
None
}
}
}
}
macro_rules! pid_decl {
($typ:ty) => {
#[doc = include_str!("../../md_doc/pid.md")]
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Pid(pub(crate) $typ);
impl From<usize> for Pid {
fn from(v: usize) -> Self {
Self(v as _)
}
}
impl From<Pid> for usize {
fn from(v: Pid) -> Self {
v.0 as _
}
}
impl FromStr for Pid {
type Err = <$typ as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(<$typ>::from_str(s)?))
}
}
impl fmt::Display for Pid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Pid {
/// Allows to convert [`Pid`][crate::Pid] into [`u32`].
///
/// ```
/// use sysinfo::Pid;
///
/// let pid = Pid::from_u32(0);
/// let value: u32 = pid.as_u32();
/// ```
pub fn as_u32(self) -> u32 {
self.0 as _
}
/// Allows to convert a [`u32`] into [`Pid`][crate::Pid].
///
/// ```
/// use sysinfo::Pid;
///
/// let pid = Pid::from_u32(0);
/// ```
pub fn from_u32(v: u32) -> Self {
Self(v as _)
}
}
};
}
cfg_if! {
if #[cfg(all(
not(feature = "unknown-ci"),
any(
target_os = "freebsd",
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
)
))] {
use libc::pid_t;
pid_decl!(pid_t);
} else {
pid_decl!(usize);
}
}
/// This enum allows you to specify when you want the related information to be updated.
///
/// For example if you only want the [`Process::exe()`] information to be refreshed only if it's not
/// already set:
///
/// ```no_run
/// use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System, UpdateKind};
///
/// let mut system = System::new();
/// system.refresh_processes_specifics(
/// ProcessesToUpdate::All,
/// true,
/// ProcessRefreshKind::nothing().with_exe(UpdateKind::OnlyIfNotSet),
/// );
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum UpdateKind {
/// Never update the related information.
#[default]
Never,
/// Always update the related information.
Always,
/// Only update the related information if it was not already set at least once.
OnlyIfNotSet,
}
impl UpdateKind {
/// If `self` is `OnlyIfNotSet`, `f` is called and its returned value is returned.
#[allow(dead_code)] // Needed for unsupported targets.
pub(crate) fn needs_update(self, f: impl Fn() -> bool) -> bool {
match self {
Self::Never => false,
Self::Always => true,
Self::OnlyIfNotSet => f(),
}
}
}
/// This enum allows you to specify if you want all processes to be updated or just
/// some of them.
///
/// Example:
///
/// ```no_run
/// use sysinfo::{ProcessesToUpdate, System, get_current_pid};
///
/// let mut system = System::new();
/// // To refresh all processes:
/// system.refresh_processes(ProcessesToUpdate::All, true);
///
/// // To refresh only the current one:
/// system.refresh_processes(
/// ProcessesToUpdate::Some(&[get_current_pid().unwrap()]),
/// true,
/// );
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProcessesToUpdate<'a> {
/// To refresh all processes.
All,
/// To refresh only the processes with the listed [`Pid`].
///
/// [`Pid`]: crate::Pid
Some(&'a [Pid]),
}
/// Used to determine what you want to refresh specifically on the [`Process`] type.
///
/// When all refresh are ruled out, a [`Process`] will still retrieve the following information:
/// * Process ID ([`Pid`])
/// * Parent process ID (on Windows it never changes though)
/// * Process name
/// * Start time
///
/// ⚠️ Just like all other refresh types, ruling out a refresh doesn't assure you that
/// the information won't be retrieved if the information is accessible without needing
/// extra computation.
///
/// ```
/// use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System};
///
/// let mut system = System::new();
///
/// // We don't want to update the CPU information.
/// system.refresh_processes_specifics(
/// ProcessesToUpdate::All,
/// true,
/// ProcessRefreshKind::everything().without_cpu(),
/// );
///
/// for (_, proc_) in system.processes() {
/// // We use a `==` comparison on float only because we know it's set to 0 here.
/// assert_eq!(proc_.cpu_usage(), 0.);
/// }
/// ```
///
/// [`Process`]: crate::Process
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ProcessRefreshKind {
cpu: bool,
disk_usage: bool,
memory: bool,
user: UpdateKind,
cwd: UpdateKind,
root: UpdateKind,
environ: UpdateKind,
cmd: UpdateKind,
exe: UpdateKind,
}
impl ProcessRefreshKind {
/// Creates a new `ProcessRefreshKind` with every refresh set to `false`.
///
/// ```
/// use sysinfo::{ProcessRefreshKind, UpdateKind};
///
/// let r = ProcessRefreshKind::nothing();
///
/// assert_eq!(r.cpu(), false);
/// assert_eq!(r.user(), UpdateKind::Never);
/// ```
pub fn nothing() -> Self {
Self::default()
}
/// Creates a new `ProcessRefreshKind` with every refresh set to `true` or
/// [`UpdateKind::OnlyIfNotSet`].
///
/// ```
/// use sysinfo::{ProcessRefreshKind, UpdateKind};
///
/// let r = ProcessRefreshKind::everything();
///
/// assert_eq!(r.cpu(), true);
/// assert_eq!(r.user(), UpdateKind::OnlyIfNotSet);
/// ```
pub fn everything() -> Self {
Self {
cpu: true,
disk_usage: true,
memory: true,
user: UpdateKind::OnlyIfNotSet,
cwd: UpdateKind::OnlyIfNotSet,
root: UpdateKind::OnlyIfNotSet,
environ: UpdateKind::OnlyIfNotSet,
cmd: UpdateKind::OnlyIfNotSet,
exe: UpdateKind::OnlyIfNotSet,
}
}
impl_get_set!(ProcessRefreshKind, cpu, with_cpu, without_cpu);
impl_get_set!(
ProcessRefreshKind,
disk_usage,
with_disk_usage,
without_disk_usage
);
impl_get_set!(
ProcessRefreshKind,
user,
with_user,
without_user,
UpdateKind,
"\
It will retrieve the following information:
* user ID
* user effective ID (if available on the platform)
* user group ID (if available on the platform)
* user effective ID (if available on the platform)"
);
impl_get_set!(ProcessRefreshKind, memory, with_memory, without_memory);
impl_get_set!(ProcessRefreshKind, cwd, with_cwd, without_cwd, UpdateKind);
impl_get_set!(
ProcessRefreshKind,
root,
with_root,
without_root,
UpdateKind
);
impl_get_set!(
ProcessRefreshKind,
environ,
with_environ,
without_environ,
UpdateKind
);
impl_get_set!(ProcessRefreshKind, cmd, with_cmd, without_cmd, UpdateKind);
impl_get_set!(ProcessRefreshKind, exe, with_exe, without_exe, UpdateKind);
}
/// Used to determine what you want to refresh specifically on the [`Cpu`] type.
///
/// ⚠️ Just like all other refresh types, ruling out a refresh doesn't assure you that
/// the information won't be retrieved if the information is accessible without needing
/// extra computation.
///
/// ```
/// use sysinfo::{CpuRefreshKind, System};
///
/// let mut system = System::new();
///
/// // We don't want to update all the CPU information.
/// system.refresh_cpu_specifics(CpuRefreshKind::everything().without_frequency());
///
/// for cpu in system.cpus() {
/// assert_eq!(cpu.frequency(), 0);
/// }
/// ```
///
/// [`Cpu`]: crate::Cpu
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CpuRefreshKind {
cpu_usage: bool,
frequency: bool,
}
impl CpuRefreshKind {
/// Creates a new `CpuRefreshKind` with every refresh set to `false`.
///
/// ```
/// use sysinfo::CpuRefreshKind;
///
/// let r = CpuRefreshKind::nothing();
///
/// assert_eq!(r.frequency(), false);
/// assert_eq!(r.cpu_usage(), false);
/// ```
pub fn nothing() -> Self {
Self::default()
}
/// Creates a new `CpuRefreshKind` with every refresh set to `true`.
///
/// ```
/// use sysinfo::CpuRefreshKind;
///
/// let r = CpuRefreshKind::everything();
///
/// assert_eq!(r.frequency(), true);
/// assert_eq!(r.cpu_usage(), true);
/// ```
pub fn everything() -> Self {
Self {
cpu_usage: true,
frequency: true,
}
}
impl_get_set!(CpuRefreshKind, cpu_usage, with_cpu_usage, without_cpu_usage);
impl_get_set!(CpuRefreshKind, frequency, with_frequency, without_frequency);
}
/// Used to determine which memory you want to refresh specifically.
///
/// ⚠️ Just like all other refresh types, ruling out a refresh doesn't assure you that
/// the information won't be retrieved if the information is accessible without needing
/// extra computation.
///
/// ```
/// use sysinfo::{MemoryRefreshKind, System};
///
/// let mut system = System::new();
///
/// // We don't want to update all memories information.
/// system.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
///
/// println!("total RAM: {}", system.total_memory());
/// println!("free RAM: {}", system.free_memory());
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MemoryRefreshKind {
ram: bool,
swap: bool,
}
impl MemoryRefreshKind {
/// Creates a new `MemoryRefreshKind` with every refresh set to `false`.
///
/// ```
/// use sysinfo::MemoryRefreshKind;
///
/// let r = MemoryRefreshKind::nothing();
///
/// assert_eq!(r.ram(), false);
/// assert_eq!(r.swap(), false);
/// ```
pub fn nothing() -> Self {
Self::default()
}
/// Creates a new `MemoryRefreshKind` with every refresh set to `true`.
///
/// ```
/// use sysinfo::MemoryRefreshKind;
///
/// let r = MemoryRefreshKind::everything();
///
/// assert_eq!(r.ram(), true);
/// assert_eq!(r.swap(), true);
/// ```
pub fn everything() -> Self {
Self {
ram: true,
swap: true,
}
}
impl_get_set!(MemoryRefreshKind, ram, with_ram, without_ram);
impl_get_set!(MemoryRefreshKind, swap, with_swap, without_swap);
}
/// Used to determine what you want to refresh specifically on the [`System`][crate::System] type.
///
/// ⚠️ Just like all other refresh types, ruling out a refresh doesn't assure you that
/// the information won't be retrieved if the information is accessible without needing
/// extra computation.
///
/// ```
/// use sysinfo::{RefreshKind, System};
///
/// // We want everything except memory.
/// let mut system = System::new_with_specifics(RefreshKind::everything().without_memory());
///
/// assert_eq!(system.total_memory(), 0);
/// # if sysinfo::IS_SUPPORTED_SYSTEM && !cfg!(feature = "apple-sandbox") {
/// assert!(system.processes().len() > 0);
/// # }
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RefreshKind {
processes: Option<ProcessRefreshKind>,
memory: Option<MemoryRefreshKind>,
cpu: Option<CpuRefreshKind>,
}
impl RefreshKind {
/// Creates a new `RefreshKind` with every refresh set to `false`/`None`.
///
/// ```
/// use sysinfo::RefreshKind;
///
/// let r = RefreshKind::nothing();
///
/// assert_eq!(r.processes().is_some(), false);
/// assert_eq!(r.memory().is_some(), false);
/// assert_eq!(r.cpu().is_some(), false);
/// ```
pub fn nothing() -> Self {
Self::default()
}
/// Creates a new `RefreshKind` with every refresh set to `true`/`Some(...)`.
///
/// ```
/// use sysinfo::RefreshKind;
///
/// let r = RefreshKind::everything();
///
/// assert_eq!(r.processes().is_some(), true);
/// assert_eq!(r.memory().is_some(), true);
/// assert_eq!(r.cpu().is_some(), true);
/// ```
pub fn everything() -> Self {
Self {
processes: Some(ProcessRefreshKind::everything()),
memory: Some(MemoryRefreshKind::everything()),
cpu: Some(CpuRefreshKind::everything()),
}
}
impl_get_set!(
RefreshKind,
processes,
with_processes,
without_processes,
ProcessRefreshKind
);
impl_get_set!(
RefreshKind,
memory,
with_memory,
without_memory,
MemoryRefreshKind
);
impl_get_set!(RefreshKind, cpu, with_cpu, without_cpu, CpuRefreshKind);
}
/// Returns the pid for the current process.
///
/// `Err` is returned in case the platform isn't supported.
///
/// ```no_run
/// use sysinfo::get_current_pid;
///
/// match get_current_pid() {
/// Ok(pid) => {
/// println!("current pid: {}", pid);
/// }
/// Err(e) => {
/// println!("failed to get current pid: {}", e);
/// }
/// }
/// ```
#[allow(clippy::unnecessary_wraps)]
pub fn get_current_pid() -> Result<Pid, &'static str> {
cfg_if! {
if #[cfg(feature = "unknown-ci")] {
fn inner() -> Result<Pid, &'static str> {
Err("Unknown platform (CI)")
}
} else if #[cfg(any(
target_os = "freebsd",
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
))] {
fn inner() -> Result<Pid, &'static str> {
unsafe { Ok(Pid(libc::getpid())) }
}
} else if #[cfg(windows)] {
fn inner() -> Result<Pid, &'static str> {
use windows::Win32::System::Threading::GetCurrentProcessId;
unsafe { Ok(Pid(GetCurrentProcessId() as _)) }
}
} else {
fn inner() -> Result<Pid, &'static str> {
Err("Unknown platform")
}
}
}
inner()
}
/// Contains all the methods of the [`Cpu`][crate::Cpu] struct.
///
/// ```no_run
/// use sysinfo::{System, RefreshKind, CpuRefreshKind};
///
/// let mut s = System::new_with_specifics(
/// RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
/// );
///
/// // Wait a bit because CPU usage is based on diff.
/// std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
/// // Refresh CPUs again to get actual value.
/// s.refresh_cpu_all();
///
/// for cpu in s.cpus() {
/// println!("{}%", cpu.cpu_usage());
/// }
/// ```
pub struct Cpu {
pub(crate) inner: CpuInner,
}
impl Cpu {
/// Returns this CPU's usage.
///
/// Note: You'll need to refresh it at least twice (diff between the first and the second is
/// how CPU usage is computed) at first if you want to have a non-zero value.
///
/// ```no_run
/// use sysinfo::{System, RefreshKind, CpuRefreshKind};
///
/// let mut s = System::new_with_specifics(
/// RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
/// );
///
/// // Wait a bit because CPU usage is based on diff.
/// std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
/// // Refresh CPUs again to get actual value.
/// s.refresh_cpu_all();
///
/// for cpu in s.cpus() {
/// println!("{}%", cpu.cpu_usage());
/// }
/// ```
pub fn cpu_usage(&self) -> f32 {
self.inner.cpu_usage()
}
/// Returns this CPU's name.
///
/// ```no_run
/// use sysinfo::{System, RefreshKind, CpuRefreshKind};
///
/// let s = System::new_with_specifics(
/// RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
/// );
/// for cpu in s.cpus() {
/// println!("{}", cpu.name());
/// }
/// ```
pub fn name(&self) -> &str {
self.inner.name()
}
/// Returns the CPU's vendor id.
///
/// ```no_run
/// use sysinfo::{System, RefreshKind, CpuRefreshKind};
///
/// let s = System::new_with_specifics(
/// RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
/// );
/// for cpu in s.cpus() {
/// println!("{}", cpu.vendor_id());
/// }
/// ```
pub fn vendor_id(&self) -> &str {
self.inner.vendor_id()
}
/// Returns the CPU's brand.
///
/// ```no_run
/// use sysinfo::{System, RefreshKind, CpuRefreshKind};
///
/// let s = System::new_with_specifics(
/// RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
/// );
/// for cpu in s.cpus() {
/// println!("{}", cpu.brand());
/// }
/// ```
pub fn brand(&self) -> &str {
self.inner.brand()
}
/// Returns the CPU's frequency.
///
/// ```no_run
/// use sysinfo::{System, RefreshKind, CpuRefreshKind};
///
/// let s = System::new_with_specifics(
/// RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
/// );
/// for cpu in s.cpus() {
/// println!("{}", cpu.frequency());
/// }
/// ```
pub fn frequency(&self) -> u64 {
self.inner.frequency()
}
}
#[cfg(test)]
mod test {
use crate::*;
use std::str::FromStr;
// In case `Process::updated` is misused, `System::refresh_processes` might remove them
// so this test ensures that it doesn't happen.
#[test]
fn check_refresh_process_update() {
if !IS_SUPPORTED_SYSTEM {
return;
}
let mut s = System::new_all();
let total = s.processes().len() as isize;
s.refresh_processes(ProcessesToUpdate::All, false);
let new_total = s.processes().len() as isize;
// There should be almost no difference in the processes count.
assert!(
(new_total - total).abs() <= 5,
"{} <= 5",
(new_total - total).abs()
);
}
#[test]
fn check_cpu_arch() {
assert!(!System::cpu_arch().is_empty());
}
// Ensure that the CPUs frequency isn't retrieved until we ask for it.
#[test]
fn check_cpu_frequency() {
if !IS_SUPPORTED_SYSTEM {
return;
}
let mut s = System::new();
s.refresh_processes(ProcessesToUpdate::All, false);
for proc_ in s.cpus() {
assert_eq!(proc_.frequency(), 0);
}
s.refresh_cpu_usage();
for proc_ in s.cpus() {
assert_eq!(proc_.frequency(), 0);
}
// In a VM, it'll fail.
if std::env::var("APPLE_CI").is_err() && std::env::var("FREEBSD_CI").is_err() {
s.refresh_cpu_specifics(CpuRefreshKind::everything());
for proc_ in s.cpus() {
assert_ne!(proc_.frequency(), 0);
}
}
}
#[test]
fn check_process_memory_usage() {
let mut s = System::new();
s.refresh_specifics(RefreshKind::everything());
if IS_SUPPORTED_SYSTEM {
// No process should have 0 as memory usage.
#[cfg(not(feature = "apple-sandbox"))]
assert!(!s.processes().iter().all(|(_, proc_)| proc_.memory() == 0));
} else {
// There should be no process, but if there is one, its memory usage should be 0.
assert!(s.processes().iter().all(|(_, proc_)| proc_.memory() == 0));
}
}
#[test]
fn check_system_implemented_traits() {
fn check<T: Sized + std::fmt::Debug + Default + Send + Sync>(_: T) {}
check(System::new());
}
#[test]
fn check_memory_usage() {
let mut s = System::new();
assert_eq!(s.total_memory(), 0);
assert_eq!(s.free_memory(), 0);
assert_eq!(s.available_memory(), 0);
assert_eq!(s.used_memory(), 0);
assert_eq!(s.total_swap(), 0);
assert_eq!(s.free_swap(), 0);
assert_eq!(s.used_swap(), 0);
s.refresh_memory();
if IS_SUPPORTED_SYSTEM {
assert!(s.total_memory() > 0);
assert!(s.used_memory() > 0);
if s.total_swap() > 0 {
// I think it's pretty safe to assume that there is still some swap left...
assert!(s.free_swap() > 0);
}
} else {
assert_eq!(s.total_memory(), 0);
assert_eq!(s.used_memory(), 0);
assert_eq!(s.total_swap(), 0);
assert_eq!(s.free_swap(), 0);
}
}
#[cfg(target_os = "linux")]
#[test]
fn check_processes_cpu_usage() {
if !IS_SUPPORTED_SYSTEM {
return;
}
let mut s = System::new();
s.refresh_processes(ProcessesToUpdate::All, false);
// All CPU usage will start at zero until the second refresh
assert!(s
.processes()
.iter()
.all(|(_, proc_)| proc_.cpu_usage() == 0.0));
// Wait a bit to update CPU usage values
std::thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL);
s.refresh_processes(ProcessesToUpdate::All, true);
assert!(s
.processes()
.iter()
.all(|(_, proc_)| proc_.cpu_usage() >= 0.0
&& proc_.cpu_usage() <= (s.cpus().len() as f32) * 100.0));
assert!(s
.processes()
.iter()
.any(|(_, proc_)| proc_.cpu_usage() > 0.0));
}
#[test]
fn check_cpu_usage() {
if !IS_SUPPORTED_SYSTEM {
return;
}
let mut s = System::new();
for _ in 0..10 {
s.refresh_cpu_usage();
// Wait a bit to update CPU usage values
std::thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL);
if s.cpus().iter().any(|c| c.cpu_usage() > 0.0) {
// All good!
return;
}
}
panic!("CPU usage is always zero...");
}
#[test]
fn check_system_info() {
// We don't want to test on unsupported systems.
if IS_SUPPORTED_SYSTEM {
assert!(!System::name()
.expect("Failed to get system name")
.is_empty());
assert!(!System::kernel_version()
.expect("Failed to get kernel version")
.is_empty());
assert!(!System::os_version()
.expect("Failed to get os version")
.is_empty());
assert!(!System::long_os_version()
.expect("Failed to get long OS version")
.is_empty());
}
assert!(!System::distribution_id().is_empty());
}
#[test]
fn check_host_name() {
// We don't want to test on unsupported systems.
if IS_SUPPORTED_SYSTEM {
assert!(System::host_name().is_some());
}
}
#[test]
fn check_refresh_process_return_value() {
// We don't want to test on unsupported systems.
if IS_SUPPORTED_SYSTEM {
let _pid = get_current_pid().expect("Failed to get current PID");
#[cfg(not(feature = "apple-sandbox"))]
{
let mut s = System::new();
// First check what happens in case the process isn't already in our process list.
assert_eq!(
s.refresh_processes(ProcessesToUpdate::Some(&[_pid]), true),
1
);
// Then check that it still returns 1 if the process is already in our process list.
assert_eq!(
s.refresh_processes(ProcessesToUpdate::Some(&[_pid]), true),
1
);
}
}
}
#[test]
fn check_cpus_number() {
let mut s = System::new();
// This information isn't retrieved by default.
assert!(s.cpus().is_empty());
if IS_SUPPORTED_SYSTEM {
// The physical cores count is recomputed every time the function is called, so the
// information must be relevant even with nothing initialized.
let physical_cores_count = s
.physical_core_count()
.expect("failed to get number of physical cores");
s.refresh_cpu_usage();
// The cpus shouldn't be empty anymore.
assert!(!s.cpus().is_empty());
// In case we are running inside a VM, it's possible to not have a physical core, only
// logical ones, which is why we don't test `physical_cores_count > 0`.
let physical_cores_count2 = s
.physical_core_count()
.expect("failed to get number of physical cores");
assert!(physical_cores_count2 <= s.cpus().len());
assert_eq!(physical_cores_count, physical_cores_count2);
} else {
assert_eq!(s.physical_core_count(), None);
}
assert!(s.physical_core_count().unwrap_or(0) <= s.cpus().len());
}
// This test only exists to ensure that the `Display` and `Debug` traits are implemented on the
// `ProcessStatus` enum on all targets.
#[test]
fn check_display_impl_process_status() {
println!("{} {:?}", ProcessStatus::Parked, ProcessStatus::Idle);
}
#[test]
#[allow(clippy::unnecessary_fallible_conversions)]
fn check_pid_from_impls() {
assert!(crate::Pid::try_from(0usize).is_ok());
// If it doesn't panic, it's fine.
let _ = crate::Pid::from(0);
assert!(crate::Pid::from_str("0").is_ok());
}
#[test]
#[allow(clippy::const_is_empty)]
fn check_nb_supported_signals() {
if IS_SUPPORTED_SYSTEM {
assert!(
!SUPPORTED_SIGNALS.is_empty(),
"SUPPORTED_SIGNALS shouldn't be empty on supported systems!"
);
} else {
assert!(
SUPPORTED_SIGNALS.is_empty(),
"SUPPORTED_SIGNALS should be empty on not support systems!"
);
}
}
}
#[cfg(doctest)]
mod doctest {
// FIXME: Can be removed once negative trait bounds are supported.
/// Check that `Process` doesn't implement `Clone`.
///
/// First we check that the "basic" code works:
///
/// ```no_run
/// use sysinfo::{Process, System};
///
/// let mut s = System::new_all();
/// let p: &Process = s.processes().values().next().unwrap();
/// ```
///
/// And now we check if it fails when we try to clone it:
///
/// ```compile_fail
/// use sysinfo::{Process, System};
///
/// let mut s = System::new_all();
/// let p: &Process = s.processes().values().next().unwrap();
/// let p = (*p).clone();
/// ```
mod process_clone {}
// FIXME: Can be removed once negative trait bounds are supported.
/// Check that `System` doesn't implement `Clone`.
///
/// First we check that the "basic" code works:
///
/// ```no_run
/// use sysinfo::{Process, System};
///
/// let s = System::new();
/// ```
///
/// And now we check if it fails when we try to clone it:
///
/// ```compile_fail
/// use sysinfo::{Process, System};
///
/// let s = System::new();
/// let s = s.clone();
/// ```
mod system_clone {}
}