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 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039
// Take a look at the license at the top of the repository in the LICENSE file.
use crate::{
utils::into_iter_mut, ComponentInner, ComponentsInner, CpuInner, NetworkDataInner,
NetworksInner, ProcessInner, SystemInner, UserInner,
};
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::ffi::OsStr;
use std::fmt;
use std::path::Path;
use std::str::FromStr;
/// 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::new())
}
/// 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::new().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::new().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(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::new().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::new().with_cpu_usage())`.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new_all();
/// 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::new().with_cpu_usage())
}
/// Refreshes CPUs frequency information.
///
/// Calling this method is the same as calling
/// `system.refresh_cpu_specifics(CpuRefreshKind::new().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::new().with_frequency())
}
/// Refreshes all information related to CPUs information.
///
/// ⚠️ 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::everything())`.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new_all();
/// s.refresh_cpu();
/// ```
///
/// [`MINIMUM_CPU_UPDATE_INTERVAL`]: crate::MINIMUM_CPU_UPDATE_INTERVAL
pub fn refresh_cpu(&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::{ProcessRefreshKind, System, UpdateKind};
/// # let mut system = System::new();
/// system.refresh_processes_specifics(
/// ProcessRefreshKind::new()
/// .with_memory()
/// .with_cpu()
/// .with_disk_usage()
/// .with_exe(UpdateKind::OnlyIfNotSet),
/// );
/// ```
///
/// ⚠️ 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::System;
///
/// let mut s = System::new_all();
/// s.refresh_processes();
/// ```
pub fn refresh_processes(&mut self) {
self.refresh_processes_specifics(
ProcessRefreshKind::new()
.with_memory()
.with_cpu()
.with_disk_usage()
.with_exe(UpdateKind::OnlyIfNotSet),
);
}
/// Gets all processes and updates the specified information.
///
/// ⚠️ 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::{ProcessRefreshKind, System};
///
/// let mut s = System::new_all();
/// s.refresh_processes_specifics(ProcessRefreshKind::new());
/// ```
pub fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) {
self.inner.refresh_processes_specifics(None, refresh_kind)
}
/// Gets specified processes and updates their information.
///
/// It does the same as:
///
/// ```no_run
/// # use sysinfo::{Pid, ProcessRefreshKind, System, UpdateKind};
/// # let mut system = System::new();
/// system.refresh_pids_specifics(
/// &[Pid::from(1), Pid::from(2)],
/// ProcessRefreshKind::new()
/// .with_memory()
/// .with_cpu()
/// .with_disk_usage()
/// .with_exe(UpdateKind::OnlyIfNotSet),
/// );
/// ```
///
/// ⚠️ 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::System;
///
/// let mut s = System::new_all();
/// s.refresh_processes();
/// ```
pub fn refresh_pids(&mut self, pids: &[Pid]) {
self.refresh_pids_specifics(
pids,
ProcessRefreshKind::new()
.with_memory()
.with_cpu()
.with_disk_usage()
.with_exe(UpdateKind::OnlyIfNotSet),
);
}
/// Gets specified processes and updates the specified information.
///
/// ⚠️ 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::{Pid, ProcessRefreshKind, System};
///
/// let mut s = System::new_all();
/// s.refresh_pids_specifics(&[Pid::from(1), Pid::from(2)], ProcessRefreshKind::new());
/// ```
pub fn refresh_pids_specifics(&mut self, pids: &[Pid], refresh_kind: ProcessRefreshKind) {
if pids.is_empty() {
return;
}
self.inner
.refresh_processes_specifics(Some(pids), refresh_kind)
}
/// Refreshes *only* the process corresponding to `pid`. Returns `false` if the process doesn't
/// exist (it will **NOT** be removed from the processes if it doesn't exist anymore). If it
/// isn't listed yet, it'll be added.
///
/// It is the same as calling:
///
/// ```no_run
/// # use sysinfo::{Pid, ProcessRefreshKind, System, UpdateKind};
/// # let mut system = System::new();
/// # let pid = Pid::from(0);
/// system.refresh_process_specifics(
/// pid,
/// ProcessRefreshKind::new()
/// .with_memory()
/// .with_cpu()
/// .with_disk_usage()
/// .with_exe(UpdateKind::OnlyIfNotSet),
/// );
/// ```
///
/// ⚠️ 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::{Pid, System};
///
/// let mut s = System::new_all();
/// s.refresh_process(Pid::from(1337));
/// ```
pub fn refresh_process(&mut self, pid: Pid) -> bool {
self.refresh_process_specifics(
pid,
ProcessRefreshKind::new()
.with_memory()
.with_cpu()
.with_disk_usage()
.with_exe(UpdateKind::OnlyIfNotSet),
)
}
/// Refreshes *only* the process corresponding to `pid`. Returns `false` if the process doesn't
/// exist (it will **NOT** be removed from the processes if it doesn't exist anymore). If it
/// isn't listed yet, it'll be added.
///
/// ⚠️ 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::{Pid, ProcessRefreshKind, System};
///
/// let mut s = System::new_all();
/// s.refresh_process_specifics(Pid::from(1337), ProcessRefreshKind::new());
/// ```
pub fn refresh_process_specifics(
&mut self,
pid: Pid,
refresh_kind: ProcessRefreshKind,
) -> bool {
self.inner.refresh_process_specifics(pid, refresh_kind)
}
/// 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") {
/// println!("{} {}", process.pid(), process.name());
/// }
/// ```
pub fn processes_by_name<'a: 'b, 'b>(
&'a self,
name: &'b str,
) -> impl Iterator<Item = &'a Process> + 'b {
self.processes()
.values()
.filter(move |val: &&Process| val.name().contains(name))
}
/// 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") {
/// println!("{} {}", process.pid(), process.name());
/// }
/// ```
pub fn processes_by_exact_name<'a: 'b, 'b>(
&'a self,
name: &'b str,
) -> impl Iterator<Item = &'a Process> + 'b {
self.processes()
.values()
.filter(move |val: &&Process| val.name() == name)
}
/// Returns "global" CPUs information (aka the addition of all the CPUs).
///
/// To have up-to-date information, you need to call [`System::refresh_cpu`] or
/// [`System::refresh_specifics`] with `cpu` enabled.
///
/// **⚠️ Important ⚠️**
///
/// Information like [`Cpu::brand`], [`Cpu::vendor_id`] or [`Cpu::frequency`]
/// are not set on the "global" CPU.
///
/// ```no_run
/// use sysinfo::{CpuRefreshKind, RefreshKind, System};
///
/// let s = System::new_with_specifics(
/// RefreshKind::new().with_cpu(CpuRefreshKind::everything()),
/// );
/// println!("{}%", s.global_cpu_info().cpu_usage());
/// ```
///
/// [`Cpu::brand`]: crate::Cpu::brand
/// [`Cpu::vendor_id`]: crate::Cpu::vendor_id
/// [`Cpu::frequency`]: crate::Cpu::frequency
pub fn global_cpu_info(&self) -> &Cpu {
self.inner.global_cpu_info()
}
/// Returns the list of the CPUs.
///
/// By default, the list of CPUs is empty until you call [`System::refresh_cpu`] or
/// [`System::refresh_specifics`] with `cpu` enabled.
///
/// ```no_run
/// use sysinfo::{CpuRefreshKind, RefreshKind, System};
///
/// let s = System::new_with_specifics(
/// RefreshKind::new().with_cpu(CpuRefreshKind::everything()),
/// );
/// 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.
///
/// **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.
///
/// **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 11.1 rather than the kernel
/// version).
///
/// **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 (e.g "MacOS 11.2 BigSur").
///
/// **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>
///
/// **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 Archicture: {:?}", System::cpu_arch());
/// ```
pub fn cpu_arch() -> Option<String> {
SystemInner::cpu_arch()
}
}
/// 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).
///
/// If you want to send 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 if the signal was sent
/// successfully.
///
/// If you just want to kill the process, use [`Process::kill`] directly.
///
/// 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)
}
/// 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) -> &str {
self.inner.name()
}
/// Returns the command line.
///
/// ```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) -> &[String] {
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) -> &[String] {
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, System};
///
/// let s = System::new_all();
/// 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.
///
/// ```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`].
///
/// ```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.
///
/// ```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()
}
/// 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 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::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::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::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);
}
}
macro_rules! impl_get_set {
($ty_name:ident, $name:ident, $with:ident, $without:ident $(, $extra_doc:literal)? $(,)?) => {
#[doc = concat!("Returns the value of the \"", stringify!($name), "\" refresh kind.")]
$(#[doc = concat!("
", $extra_doc, "
")])?
#[doc = concat!("
```
use sysinfo::", stringify!($ty_name), ";
let r = ", stringify!($ty_name), "::new();
assert_eq!(r.", stringify!($name), "(), false);
let r = r.with_", stringify!($name), "();
assert_eq!(r.", stringify!($name), "(), true);
let r = r.without_", stringify!($name), "();
assert_eq!(r.", stringify!($name), "(), false);
```")]
pub fn $name(&self) -> bool {
self.$name
}
#[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `true`.
```
use sysinfo::", stringify!($ty_name), ";
let r = ", stringify!($ty_name), "::new();
assert_eq!(r.", stringify!($name), "(), false);
let r = r.with_", stringify!($name), "();
assert_eq!(r.", stringify!($name), "(), true);
```")]
#[must_use]
pub fn $with(mut self) -> Self {
self.$name = true;
self
}
#[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `false`.
```
use sysinfo::", stringify!($ty_name), ";
let r = ", stringify!($ty_name), "::everything();
assert_eq!(r.", stringify!($name), "(), true);
let r = r.without_", stringify!($name), "();
assert_eq!(r.", stringify!($name), "(), false);
```")]
#[must_use]
pub fn $without(mut self) -> Self {
self.$name = false;
self
}
};
// To handle `UpdateKind`.
($ty_name:ident, $name:ident, $with:ident, $without:ident, UpdateKind $(, $extra_doc:literal)? $(,)?) => {
#[doc = concat!("Returns the value of the \"", stringify!($name), "\" refresh kind.")]
$(#[doc = concat!("
", $extra_doc, "
")])?
#[doc = concat!("
```
use sysinfo::{", stringify!($ty_name), ", UpdateKind};
let r = ", stringify!($ty_name), "::new();
assert_eq!(r.", stringify!($name), "(), UpdateKind::Never);
let r = r.with_", stringify!($name), "(UpdateKind::OnlyIfNotSet);
assert_eq!(r.", stringify!($name), "(), UpdateKind::OnlyIfNotSet);
let r = r.without_", stringify!($name), "();
assert_eq!(r.", stringify!($name), "(), UpdateKind::Never);
```")]
pub fn $name(&self) -> UpdateKind {
self.$name
}
#[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind.
```
use sysinfo::{", stringify!($ty_name), ", UpdateKind};
let r = ", stringify!($ty_name), "::new();
assert_eq!(r.", stringify!($name), "(), UpdateKind::Never);
let r = r.with_", stringify!($name), "(UpdateKind::OnlyIfNotSet);
assert_eq!(r.", stringify!($name), "(), UpdateKind::OnlyIfNotSet);
```")]
#[must_use]
pub fn $with(mut self, kind: UpdateKind) -> Self {
self.$name = kind;
self
}
#[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `UpdateKind::Never`.
```
use sysinfo::{", stringify!($ty_name), ", UpdateKind};
let r = ", stringify!($ty_name), "::everything();
assert_eq!(r.", stringify!($name), "(), UpdateKind::OnlyIfNotSet);
let r = r.without_", stringify!($name), "();
assert_eq!(r.", stringify!($name), "(), UpdateKind::Never);
```")]
#[must_use]
pub fn $without(mut self) -> Self {
self.$name = UpdateKind::Never;
self
}
};
// To handle `*RefreshKind`.
($ty_name:ident, $name:ident, $with:ident, $without:ident, $typ:ty $(,)?) => {
#[doc = concat!("Returns the value of the \"", stringify!($name), "\" refresh kind.
```
use sysinfo::{", stringify!($ty_name), ", ", stringify!($typ), "};
let r = ", stringify!($ty_name), "::new();
assert_eq!(r.", stringify!($name), "().is_some(), false);
let r = r.with_", stringify!($name), "(", stringify!($typ), "::everything());
assert_eq!(r.", stringify!($name), "().is_some(), true);
let r = r.without_", stringify!($name), "();
assert_eq!(r.", stringify!($name), "().is_some(), false);
```")]
pub fn $name(&self) -> Option<$typ> {
self.$name
}
#[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `Some(...)`.
```
use sysinfo::{", stringify!($ty_name), ", ", stringify!($typ), "};
let r = ", stringify!($ty_name), "::new();
assert_eq!(r.", stringify!($name), "().is_some(), false);
let r = r.with_", stringify!($name), "(", stringify!($typ), "::everything());
assert_eq!(r.", stringify!($name), "().is_some(), true);
```")]
#[must_use]
pub fn $with(mut self, kind: $typ) -> Self {
self.$name = Some(kind);
self
}
#[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `None`.
```
use sysinfo::", stringify!($ty_name), ";
let r = ", stringify!($ty_name), "::everything();
assert_eq!(r.", stringify!($name), "().is_some(), true);
let r = r.without_", stringify!($name), "();
assert_eq!(r.", stringify!($name), "().is_some(), false);
```")]
#[must_use]
pub fn $without(mut self) -> Self {
self.$name = None;
self
}
};
}
/// 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::{ProcessRefreshKind, System, UpdateKind};
///
/// let mut system = System::new();
/// system.refresh_processes_specifics(
/// ProcessRefreshKind::new().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(),
}
}
}
/// 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::{ProcessRefreshKind, System};
///
/// let mut system = System::new();
///
/// // We don't want to update the CPU information.
/// system.refresh_processes_specifics(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::new();
///
/// assert_eq!(r.cpu(), false);
/// assert_eq!(r.user(), UpdateKind::Never);
/// ```
pub fn new() -> 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::new();
///
/// assert_eq!(r.frequency(), false);
/// assert_eq!(r.cpu_usage(), false);
/// ```
pub fn new() -> 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::new().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::new();
///
/// assert_eq!(r.ram(), false);
/// assert_eq!(r.swap(), false);
/// ```
pub fn new() -> 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::new();
///
/// assert_eq!(r.processes().is_some(), false);
/// assert_eq!(r.memory().is_some(), false);
/// assert_eq!(r.cpu().is_some(), false);
/// ```
pub fn new() -> 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);
}
/// Interacting with network interfaces.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for (interface_name, network) in &networks {
/// println!("[{interface_name}]: {network:?}");
/// }
/// ```
pub struct Networks {
pub(crate) inner: NetworksInner,
}
impl<'a> IntoIterator for &'a Networks {
type Item = (&'a String, &'a NetworkData);
type IntoIter = std::collections::hash_map::Iter<'a, String, NetworkData>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl Default for Networks {
fn default() -> Self {
Networks::new()
}
}
impl Networks {
/// Creates a new empty [`Networks`][crate::Networks] type.
///
/// If you want it to be filled directly, take a look at [`Networks::new_with_refreshed_list`].
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let mut networks = Networks::new();
/// networks.refresh_list();
/// for (interface_name, network) in &networks {
/// println!("[{interface_name}]: {network:?}");
/// }
/// ```
pub fn new() -> Self {
Self {
inner: NetworksInner::new(),
}
}
/// Creates a new [`Networks`][crate::Networks] type with the disk list
/// loaded. It is a combination of [`Networks::new`] and
/// [`Networks::refresh_list`].
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for network in &networks {
/// println!("{network:?}");
/// }
/// ```
pub fn new_with_refreshed_list() -> Self {
let mut networks = Self::new();
networks.refresh_list();
networks
}
/// Returns the network interfaces map.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for network in networks.list() {
/// println!("{network:?}");
/// }
/// ```
pub fn list(&self) -> &HashMap<String, NetworkData> {
self.inner.list()
}
/// Refreshes the network interfaces list.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let mut networks = Networks::new();
/// networks.refresh_list();
/// ```
pub fn refresh_list(&mut self) {
self.inner.refresh_list()
}
/// Refreshes the network interfaces' content. If you didn't run [`Networks::refresh_list`]
/// before, calling this method won't do anything as no interfaces are present.
///
/// ⚠️ If a network interface is added or removed, this method won't take it into account. Use
/// [`Networks::refresh_list`] instead.
///
/// ⚠️ If you didn't call [`Networks::refresh_list`] beforehand, this method will do nothing
/// as the network list will be empty.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let mut networks = Networks::new_with_refreshed_list();
/// // Wait some time...? Then refresh the data of each network.
/// networks.refresh();
/// ```
pub fn refresh(&mut self) {
self.inner.refresh()
}
}
impl std::ops::Deref for Networks {
type Target = HashMap<String, NetworkData>;
fn deref(&self) -> &Self::Target {
self.list()
}
}
/// Getting volume of received and transmitted data.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for (interface_name, network) in &networks {
/// println!("[{interface_name}] {network:?}");
/// }
/// ```
pub struct NetworkData {
pub(crate) inner: NetworkDataInner,
}
impl NetworkData {
/// Returns the number of received bytes since the last refresh.
///
/// If you want the total number of bytes received, take a look at the
/// [`total_received`](NetworkData::total_received) method.
///
/// ```no_run
/// use sysinfo::Networks;
/// use std::{thread, time};
///
/// let mut networks = Networks::new_with_refreshed_list();
/// // Waiting a bit to get data from network...
/// thread::sleep(time::Duration::from_millis(10));
/// // Refreshing again to generate diff.
/// networks.refresh();
///
/// for (interface_name, network) in &networks {
/// println!("in: {} B", network.received());
/// }
/// ```
pub fn received(&self) -> u64 {
self.inner.received()
}
/// Returns the total number of received bytes.
///
/// If you want the amount of received bytes since the last refresh, take a look at the
/// [`received`](NetworkData::received) method.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for (interface_name, network) in &networks {
/// println!("in: {} B", network.total_received());
/// }
/// ```
pub fn total_received(&self) -> u64 {
self.inner.total_received()
}
/// Returns the number of transmitted bytes since the last refresh.
///
/// If you want the total number of bytes transmitted, take a look at the
/// [`total_transmitted`](NetworkData::total_transmitted) method.
///
/// ```no_run
/// use sysinfo::Networks;
/// use std::{thread, time};
///
/// let mut networks = Networks::new_with_refreshed_list();
/// // Waiting a bit to get data from network...
/// thread::sleep(time::Duration::from_millis(10));
/// // Refreshing again to generate diff.
/// networks.refresh();
///
/// for (interface_name, network) in &networks {
/// println!("out: {} B", network.transmitted());
/// }
/// ```
pub fn transmitted(&self) -> u64 {
self.inner.transmitted()
}
/// Returns the total number of transmitted bytes.
///
/// If you want the amount of transmitted bytes since the last refresh, take a look at the
/// [`transmitted`](NetworkData::transmitted) method.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for (interface_name, network) in &networks {
/// println!("out: {} B", network.total_transmitted());
/// }
/// ```
pub fn total_transmitted(&self) -> u64 {
self.inner.total_transmitted()
}
/// Returns the number of incoming packets since the last refresh.
///
/// If you want the total number of packets received, take a look at the
/// [`total_packets_received`](NetworkData::total_packets_received) method.
///
/// ```no_run
/// use sysinfo::Networks;
/// use std::{thread, time};
///
/// let mut networks = Networks::new_with_refreshed_list();
/// // Waiting a bit to get data from network...
/// thread::sleep(time::Duration::from_millis(10));
/// // Refreshing again to generate diff.
/// networks.refresh();
///
/// for (interface_name, network) in &networks {
/// println!("in: {}", network.packets_received());
/// }
/// ```
pub fn packets_received(&self) -> u64 {
self.inner.packets_received()
}
/// Returns the total number of incoming packets.
///
/// If you want the amount of received packets since the last refresh, take a look at the
/// [`packets_received`](NetworkData::packets_received) method.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for (interface_name, network) in &networks {
/// println!("in: {}", network.total_packets_received());
/// }
/// ```
pub fn total_packets_received(&self) -> u64 {
self.inner.total_packets_received()
}
/// Returns the number of outcoming packets since the last refresh.
///
/// If you want the total number of packets transmitted, take a look at the
/// [`total_packets_transmitted`](NetworkData::total_packets_transmitted) method.
///
/// ```no_run
/// use sysinfo::Networks;
/// use std::{thread, time};
///
/// let mut networks = Networks::new_with_refreshed_list();
/// // Waiting a bit to get data from network...
/// thread::sleep(time::Duration::from_millis(10));
/// // Refreshing again to generate diff.
/// networks.refresh();
///
/// for (interface_name, network) in &networks {
/// println!("out: {}", network.packets_transmitted());
/// }
/// ```
pub fn packets_transmitted(&self) -> u64 {
self.inner.packets_transmitted()
}
/// Returns the total number of outcoming packets.
///
/// If you want the amount of transmitted packets since the last refresh, take a look at the
/// [`packets_transmitted`](NetworkData::packets_transmitted) method.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for (interface_name, network) in &networks {
/// println!("out: {}", network.total_packets_transmitted());
/// }
/// ```
pub fn total_packets_transmitted(&self) -> u64 {
self.inner.total_packets_transmitted()
}
/// Returns the number of incoming errors since the last refresh.
///
/// If you want the total number of errors on received packets, take a look at the
/// [`total_errors_on_received`](NetworkData::total_errors_on_received) method.
///
/// ```no_run
/// use sysinfo::Networks;
/// use std::{thread, time};
///
/// let mut networks = Networks::new_with_refreshed_list();
/// // Waiting a bit to get data from network...
/// thread::sleep(time::Duration::from_millis(10));
/// // Refreshing again to generate diff.
/// networks.refresh();
///
/// for (interface_name, network) in &networks {
/// println!("in: {}", network.errors_on_received());
/// }
/// ```
pub fn errors_on_received(&self) -> u64 {
self.inner.errors_on_received()
}
/// Returns the total number of incoming errors.
///
/// If you want the amount of errors on received packets since the last refresh, take a look at
/// the [`errors_on_received`](NetworkData::errors_on_received) method.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for (interface_name, network) in &networks {
/// println!("in: {}", network.total_errors_on_received());
/// }
/// ```
pub fn total_errors_on_received(&self) -> u64 {
self.inner.total_errors_on_received()
}
/// Returns the number of outcoming errors since the last refresh.
///
/// If you want the total number of errors on transmitted packets, take a look at the
/// [`total_errors_on_transmitted`](NetworkData::total_errors_on_transmitted) method.
///
/// ```no_run
/// use sysinfo::Networks;
/// use std::{thread, time};
///
/// let mut networks = Networks::new_with_refreshed_list();
/// // Waiting a bit to get data from network...
/// thread::sleep(time::Duration::from_millis(10));
/// // Refreshing again to generate diff.
/// networks.refresh();
///
/// for (interface_name, network) in &networks {
/// println!("out: {}", network.errors_on_transmitted());
/// }
/// ```
pub fn errors_on_transmitted(&self) -> u64 {
self.inner.errors_on_transmitted()
}
/// Returns the total number of outcoming errors.
///
/// If you want the amount of errors on transmitted packets since the last refresh, take a look at
/// the [`errors_on_transmitted`](NetworkData::errors_on_transmitted) method.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let networks = Networks::new_with_refreshed_list();
/// for (interface_name, network) in &networks {
/// println!("out: {}", network.total_errors_on_transmitted());
/// }
/// ```
pub fn total_errors_on_transmitted(&self) -> u64 {
self.inner.total_errors_on_transmitted()
}
/// Returns the MAC address associated to current interface.
///
/// ```no_run
/// use sysinfo::Networks;
///
/// let mut networks = Networks::new_with_refreshed_list();
/// for (interface_name, network) in &networks {
/// println!("MAC address: {}", network.mac_address());
/// }
/// ```
pub fn mac_address(&self) -> MacAddr {
self.inner.mac_address()
}
}
/// Struct containing a disk information.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("{:?}: {:?}", disk.name(), disk.kind());
/// }
/// ```
pub struct Disk {
pub(crate) inner: crate::DiskInner,
}
impl Disk {
/// Returns the kind of disk.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("[{:?}] {:?}", disk.name(), disk.kind());
/// }
/// ```
pub fn kind(&self) -> DiskKind {
self.inner.kind()
}
/// Returns the disk name.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("{:?}", disk.name());
/// }
/// ```
pub fn name(&self) -> &OsStr {
self.inner.name()
}
/// Returns the file system used on this disk (so for example: `EXT4`, `NTFS`, etc...).
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("[{:?}] {:?}", disk.name(), disk.file_system());
/// }
/// ```
pub fn file_system(&self) -> &OsStr {
self.inner.file_system()
}
/// Returns the mount point of the disk (`/` for example).
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("[{:?}] {:?}", disk.name(), disk.mount_point());
/// }
/// ```
pub fn mount_point(&self) -> &Path {
self.inner.mount_point()
}
/// Returns the total disk size, in bytes.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("[{:?}] {}B", disk.name(), disk.total_space());
/// }
/// ```
pub fn total_space(&self) -> u64 {
self.inner.total_space()
}
/// Returns the available disk size, in bytes.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("[{:?}] {}B", disk.name(), disk.available_space());
/// }
/// ```
pub fn available_space(&self) -> u64 {
self.inner.available_space()
}
/// Returns `true` if the disk is removable.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("[{:?}] {}", disk.name(), disk.is_removable());
/// }
/// ```
pub fn is_removable(&self) -> bool {
self.inner.is_removable()
}
/// Updates the disk' information.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let mut disks = Disks::new_with_refreshed_list();
/// for disk in disks.list_mut() {
/// disk.refresh();
/// }
/// ```
pub fn refresh(&mut self) -> bool {
self.inner.refresh()
}
}
/// Disks interface.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("{disk:?}");
/// }
/// ```
///
/// ⚠️ Note that tmpfs mounts are excluded by default under Linux.
/// To display tmpfs mount points, the `linux-tmpfs` feature must be enabled.
///
/// ⚠️ Note that network devices are excluded by default under Linux.
/// To display mount points using the CIFS and NFS protocols, the `linux-netdevs`
/// feature must be enabled. Note, however, that sysinfo may hang under certain
/// circumstances. For example, if a CIFS or NFS share has been mounted with
/// the _hard_ option, but the connection has an error, such as the share server has stopped.
pub struct Disks {
inner: crate::DisksInner,
}
impl Default for Disks {
fn default() -> Self {
Self::new()
}
}
impl From<Disks> for Vec<Disk> {
fn from(disks: Disks) -> Vec<Disk> {
disks.inner.into_vec()
}
}
impl From<Vec<Disk>> for Disks {
fn from(disks: Vec<Disk>) -> Self {
Self {
inner: crate::DisksInner::from_vec(disks),
}
}
}
impl<'a> IntoIterator for &'a Disks {
type Item = &'a Disk;
type IntoIter = std::slice::Iter<'a, Disk>;
fn into_iter(self) -> Self::IntoIter {
self.list().iter()
}
}
impl<'a> IntoIterator for &'a mut Disks {
type Item = &'a mut Disk;
type IntoIter = std::slice::IterMut<'a, Disk>;
fn into_iter(self) -> Self::IntoIter {
self.list_mut().iter_mut()
}
}
impl Disks {
/// Creates a new empty [`Disks`][crate::Disks] type.
///
/// If you want it to be filled directly, take a look at [`Disks::new_with_refreshed_list`].
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let mut disks = Disks::new();
/// disks.refresh_list();
/// for disk in disks.list() {
/// println!("{disk:?}");
/// }
/// ```
pub fn new() -> Self {
Self {
inner: crate::DisksInner::new(),
}
}
/// Creates a new [`Disks`][crate::Disks] type with the disk list loaded.
/// It is a combination of [`Disks::new`] and [`Disks::refresh_list`].
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let mut disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("{disk:?}");
/// }
/// ```
pub fn new_with_refreshed_list() -> Self {
let mut disks = Self::new();
disks.refresh_list();
disks
}
/// Returns the disks list.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("{disk:?}");
/// }
/// ```
pub fn list(&self) -> &[Disk] {
self.inner.list()
}
/// Returns the disks list.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let mut disks = Disks::new_with_refreshed_list();
/// for disk in disks.list_mut() {
/// disk.refresh();
/// println!("{disk:?}");
/// }
/// ```
pub fn list_mut(&mut self) -> &mut [Disk] {
self.inner.list_mut()
}
/// Refreshes the listed disks' information.
///
/// ⚠️ If a disk is added or removed, this method won't take it into account. Use
/// [`Disks::refresh_list`] instead.
///
/// ⚠️ If you didn't call [`Disks::refresh_list`] beforehand, this method will do nothing as
/// the disk list will be empty.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let mut disks = Disks::new_with_refreshed_list();
/// // We wait some time...?
/// disks.refresh();
/// ```
pub fn refresh(&mut self) {
for disk in self.list_mut() {
disk.refresh();
}
}
/// The disk list will be emptied then completely recomputed.
///
/// ## Linux
///
/// ⚠️ On Linux, the [NFS](https://en.wikipedia.org/wiki/Network_File_System) file
/// systems are ignored and the information of a mounted NFS **cannot** be obtained
/// via [`Disks::refresh_list`]. This is due to the fact that I/O function
/// `statvfs` used by [`Disks::refresh_list`] is blocking and
/// [may hang](https://github.com/GuillaumeGomez/sysinfo/pull/876) in some cases,
/// requiring to call `systemctl stop` to terminate the NFS service from the remote
/// server in some cases.
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let mut disks = Disks::new();
/// disks.refresh_list();
/// ```
pub fn refresh_list(&mut self) {
self.inner.refresh_list();
}
}
impl std::ops::Deref for Disks {
type Target = [Disk];
fn deref(&self) -> &Self::Target {
self.list()
}
}
impl std::ops::DerefMut for Disks {
fn deref_mut(&mut self) -> &mut Self::Target {
self.list_mut()
}
}
/// Enum containing the different supported kinds of disks.
///
/// This type is returned by [`Disk::kind`](`crate::Disk::kind`).
///
/// ```no_run
/// use sysinfo::Disks;
///
/// let disks = Disks::new_with_refreshed_list();
/// for disk in disks.list() {
/// println!("{:?}: {:?}", disk.name(), disk.kind());
/// }
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum DiskKind {
/// HDD type.
HDD,
/// SSD type.
SSD,
/// Unknown type.
Unknown(isize),
}
impl fmt::Display for DiskKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match *self {
DiskKind::HDD => "HDD",
DiskKind::SSD => "SSD",
_ => "Unknown",
})
}
}
/// Interacting with users.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let mut users = Users::new();
/// for user in users.list() {
/// println!("{} is in {} groups", user.name(), user.groups().len());
/// }
/// ```
pub struct Users {
users: Vec<User>,
}
impl Default for Users {
fn default() -> Self {
Self::new()
}
}
impl From<Users> for Vec<User> {
fn from(users: Users) -> Self {
users.users
}
}
impl From<Vec<User>> for Users {
fn from(users: Vec<User>) -> Self {
Self { users }
}
}
impl std::ops::Deref for Users {
type Target = [User];
fn deref(&self) -> &Self::Target {
self.list()
}
}
impl std::ops::DerefMut for Users {
fn deref_mut(&mut self) -> &mut Self::Target {
self.list_mut()
}
}
impl<'a> IntoIterator for &'a Users {
type Item = &'a User;
type IntoIter = std::slice::Iter<'a, User>;
fn into_iter(self) -> Self::IntoIter {
self.list().iter()
}
}
impl<'a> IntoIterator for &'a mut Users {
type Item = &'a mut User;
type IntoIter = std::slice::IterMut<'a, User>;
fn into_iter(self) -> Self::IntoIter {
self.list_mut().iter_mut()
}
}
impl Users {
/// Creates a new empty [`Users`][crate::Users] type.
///
/// If you want it to be filled directly, take a look at [`Users::new_with_refreshed_list`].
///
/// ```no_run
/// use sysinfo::Users;
///
/// let mut users = Users::new();
/// users.refresh_list();
/// for user in users.list() {
/// println!("{user:?}");
/// }
/// ```
pub fn new() -> Self {
Self { users: Vec::new() }
}
/// Creates a new [`Users`][crate::Users] type with the user list loaded.
/// It is a combination of [`Users::new`] and [`Users::refresh_list`].
///
/// ```no_run
/// use sysinfo::Users;
///
/// let mut users = Users::new_with_refreshed_list();
/// for user in users.list() {
/// println!("{user:?}");
/// }
/// ```
pub fn new_with_refreshed_list() -> Self {
let mut users = Self::new();
users.refresh_list();
users
}
/// Returns the users list.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let users = Users::new_with_refreshed_list();
/// for user in users.list() {
/// println!("{user:?}");
/// }
/// ```
pub fn list(&self) -> &[User] {
&self.users
}
/// Returns the users list.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let mut users = Users::new_with_refreshed_list();
/// users.list_mut().sort_by(|user1, user2| {
/// user1.name().partial_cmp(user2.name()).unwrap()
/// });
/// ```
pub fn list_mut(&mut self) -> &mut [User] {
&mut self.users
}
/// The user list will be emptied then completely recomputed.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let mut users = Users::new();
/// users.refresh_list();
/// ```
pub fn refresh_list(&mut self) {
crate::sys::get_users(&mut self.users);
}
/// Returns the [`User`] matching the given `user_id`.
///
/// **Important**: The user list must be filled before using this method, otherwise it will
/// always return `None` (through the `refresh_*` methods).
///
/// It is a shorthand for:
///
/// ```ignore
/// # use sysinfo::Users;
/// let users = Users::new_with_refreshed_list();
/// users.list().find(|user| user.id() == user_id);
/// ```
///
/// Full example:
///
/// ```no_run
/// use sysinfo::{Pid, System, Users};
///
/// let mut s = System::new_all();
/// let users = Users::new_with_refreshed_list();
///
/// if let Some(process) = s.process(Pid::from(1337)) {
/// if let Some(user_id) = process.user_id() {
/// println!("User for process 1337: {:?}", users.get_user_by_id(user_id));
/// }
/// }
/// ```
pub fn get_user_by_id(&self, user_id: &Uid) -> Option<&User> {
self.users.iter().find(|user| user.id() == user_id)
}
}
/// Interacting with groups.
///
/// ```no_run
/// use sysinfo::Groups;
///
/// let mut groups = Groups::new();
/// for group in groups.list() {
/// println!("{}", group.name());
/// }
/// ```
pub struct Groups {
groups: Vec<Group>,
}
impl Default for Groups {
fn default() -> Self {
Self::new()
}
}
impl From<Groups> for Vec<Group> {
fn from(groups: Groups) -> Self {
groups.groups
}
}
impl From<Vec<Group>> for Groups {
fn from(groups: Vec<Group>) -> Self {
Self { groups }
}
}
impl std::ops::Deref for Groups {
type Target = [Group];
fn deref(&self) -> &Self::Target {
self.list()
}
}
impl std::ops::DerefMut for Groups {
fn deref_mut(&mut self) -> &mut Self::Target {
self.list_mut()
}
}
impl<'a> IntoIterator for &'a Groups {
type Item = &'a Group;
type IntoIter = std::slice::Iter<'a, Group>;
fn into_iter(self) -> Self::IntoIter {
self.list().iter()
}
}
impl<'a> IntoIterator for &'a mut Groups {
type Item = &'a mut Group;
type IntoIter = std::slice::IterMut<'a, Group>;
fn into_iter(self) -> Self::IntoIter {
self.list_mut().iter_mut()
}
}
impl Groups {
/// Creates a new empty [`Groups`][crate::Groups] type.
///
/// If you want it to be filled directly, take a look at [`Groups::new_with_refreshed_list`].
///
/// ```no_run
/// use sysinfo::Groups;
///
/// let mut groups = Groups::new();
/// groups.refresh_list();
/// for group in groups.list() {
/// println!("{group:?}");
/// }
/// ```
pub fn new() -> Self {
Self { groups: Vec::new() }
}
/// Creates a new [`Groups`][crate::Groups] type with the user list loaded.
/// It is a combination of [`Groups::new`] and [`Groups::refresh_list`].
///
/// ```no_run
/// use sysinfo::Groups;
///
/// let mut groups = Groups::new_with_refreshed_list();
/// for group in groups.list() {
/// println!("{group:?}");
/// }
/// ```
pub fn new_with_refreshed_list() -> Self {
let mut groups = Self::new();
groups.refresh_list();
groups
}
/// Returns the users list.
///
/// ```no_run
/// use sysinfo::Groups;
///
/// let groups = Groups::new_with_refreshed_list();
/// for group in groups.list() {
/// println!("{group:?}");
/// }
/// ```
pub fn list(&self) -> &[Group] {
&self.groups
}
/// Returns the groups list.
///
/// ```no_run
/// use sysinfo::Groups;
///
/// let mut groups = Groups::new_with_refreshed_list();
/// groups.list_mut().sort_by(|user1, user2| {
/// user1.name().partial_cmp(user2.name()).unwrap()
/// });
/// ```
pub fn list_mut(&mut self) -> &mut [Group] {
&mut self.groups
}
/// The group list will be emptied then completely recomputed.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let mut users = Users::new();
/// users.refresh_list();
/// ```
pub fn refresh_list(&mut self) {
crate::sys::get_groups(&mut self.groups);
}
}
/// 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,
}
/// 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,
}
macro_rules! xid {
($(#[$outer:meta])+ $name:ident, $type:ty $(, $trait:ty)?) => {
$(#[$outer])+
#[repr(transparent)]
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct $name(pub(crate) $type);
impl std::ops::Deref for $name {
type Target = $type;
fn deref(&self) -> &Self::Target {
&self.0
}
}
$(
impl TryFrom<usize> for $name {
type Error = <$type as TryFrom<usize>>::Error;
fn try_from(t: usize) -> Result<Self, <$type as TryFrom<usize>>::Error> {
Ok(Self(<$type>::try_from(t)?))
}
}
impl $trait for $name {
type Err = <$type as FromStr>::Err;
fn from_str(t: &str) -> Result<Self, <$type as FromStr>::Err> {
Ok(Self(<$type>::from_str(t)?))
}
}
)?
};
}
macro_rules! uid {
($type:ty$(, $trait:ty)?) => {
xid!(
/// A user id wrapping a platform specific type.
Uid,
$type
$(, $trait)?
);
};
}
macro_rules! gid {
($type:ty) => {
xid!(
/// A group id wrapping a platform specific type.
#[derive(Copy)]
Gid,
$type,
FromStr
);
};
}
cfg_if::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",
)
))] {
uid!(libc::uid_t, FromStr);
gid!(libc::gid_t);
} else if #[cfg(windows)] {
uid!(crate::windows::Sid);
gid!(u32);
// Manual implementation outside of the macro...
impl FromStr for Uid {
type Err = <crate::windows::Sid as FromStr>::Err;
fn from_str(t: &str) -> Result<Self, Self::Err> {
Ok(Self(t.parse()?))
}
}
} else {
uid!(u32, FromStr);
gid!(u32);
}
}
/// Type containing user information.
///
/// It is returned by [`Users`][crate::Users].
///
/// ```no_run
/// use sysinfo::Users;
///
/// let users = Users::new_with_refreshed_list();
/// for user in users.list() {
/// println!("{:?}", user);
/// }
/// ```
pub struct User {
pub(crate) inner: UserInner,
}
impl PartialEq for User {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
&& self.group_id() == other.group_id()
&& self.name() == other.name()
}
}
impl Eq for User {}
impl PartialOrd for User {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for User {
fn cmp(&self, other: &Self) -> Ordering {
self.name().cmp(other.name())
}
}
impl User {
/// Returns the ID of the user.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let users = Users::new_with_refreshed_list();
/// for user in users.list() {
/// println!("{:?}", *user.id());
/// }
/// ```
pub fn id(&self) -> &Uid {
self.inner.id()
}
/// Returns the group ID of the user.
///
/// ⚠️ This information is not set on Windows. Windows doesn't have a `username` specific
/// group assigned to the user. They do however have unique
/// [Security Identifiers](https://docs.microsoft.com/en-us/windows/win32/secauthz/security-identifiers)
/// made up of various [Components](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-components).
/// Pieces of the SID may be a candidate for this field, but it doesn't map well to a single
/// group ID.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let users = Users::new_with_refreshed_list();
/// for user in users.list() {
/// println!("{}", *user.group_id());
/// }
/// ```
pub fn group_id(&self) -> Gid {
self.inner.group_id()
}
/// Returns the name of the user.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let users = Users::new_with_refreshed_list();
/// for user in users.list() {
/// println!("{}", user.name());
/// }
/// ```
pub fn name(&self) -> &str {
self.inner.name()
}
/// Returns the groups of the user.
///
/// ⚠️ This is computed every time this method is called.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let users = Users::new_with_refreshed_list();
/// for user in users.list() {
/// println!("{} is in {:?}", user.name(), user.groups());
/// }
/// ```
pub fn groups(&self) -> Vec<Group> {
self.inner.groups()
}
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(crate) struct GroupInner {
pub(crate) id: Gid,
pub(crate) name: String,
}
/// Type containing group information.
///
/// It is returned by [`User::groups`] or [`Groups::list`].
///
/// ```no_run
/// use sysinfo::Users;
///
/// let mut users = Users::new_with_refreshed_list();
///
/// for user in users.list() {
/// println!(
/// "user: (ID: {:?}, group ID: {:?}, name: {:?})",
/// user.id(),
/// user.group_id(),
/// user.name(),
/// );
/// for group in user.groups() {
/// println!("group: (ID: {:?}, name: {:?})", group.id(), group.name());
/// }
/// }
/// ```
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Group {
pub(crate) inner: GroupInner,
}
impl Group {
/// Returns the ID of the group.
///
/// ⚠️ This information is not set on Windows.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let mut users = Users::new_with_refreshed_list();
///
/// for user in users.list() {
/// for group in user.groups() {
/// println!("{:?}", group.id());
/// }
/// }
/// ```
pub fn id(&self) -> &Gid {
self.inner.id()
}
/// Returns the name of the group.
///
/// ```no_run
/// use sysinfo::Users;
///
/// let mut users = Users::new_with_refreshed_list();
///
/// for user in users.list() {
/// for group in user.groups() {
/// println!("{}", group.name());
/// }
/// }
/// ```
pub fn name(&self) -> &str {
self.inner.name()
}
}
/// Type containing read and written bytes.
///
/// It is returned by [`Process::disk_usage`][crate::Process::disk_usage].
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// for (pid, process) in s.processes() {
/// let disk_usage = process.disk_usage();
/// println!("[{}] read bytes : new/total => {}/{} B",
/// pid,
/// disk_usage.read_bytes,
/// disk_usage.total_read_bytes,
/// );
/// println!("[{}] written bytes: new/total => {}/{} B",
/// pid,
/// disk_usage.written_bytes,
/// disk_usage.total_written_bytes,
/// );
/// }
/// ```
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub struct DiskUsage {
/// Total number of written bytes.
pub total_written_bytes: u64,
/// Number of written bytes since the last refresh.
pub written_bytes: u64,
/// Total number of read bytes.
pub total_read_bytes: u64,
/// Number of read bytes since the last refresh.
pub read_bytes: 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,
}
/// 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::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()
}
/// MAC address for network interface.
///
/// It is returned by [`NetworkData::mac_address`][crate::NetworkData::mac_address].
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub struct MacAddr(pub [u8; 6]);
impl MacAddr {
/// A `MacAddr` with all bytes set to `0`.
pub const UNSPECIFIED: Self = MacAddr([0; 6]);
/// Checks if this `MacAddr` has all bytes equal to `0`.
pub fn is_unspecified(&self) -> bool {
self == &MacAddr::UNSPECIFIED
}
}
impl fmt::Display for MacAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let data = &self.0;
write!(
f,
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
data[0], data[1], data[2], data[3], data[4], data[5],
)
}
}
/// Interacting with components.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let components = Components::new_with_refreshed_list();
/// for component in &components {
/// println!("{component:?}");
/// }
/// ```
pub struct Components {
pub(crate) inner: ComponentsInner,
}
impl Default for Components {
fn default() -> Self {
Self::new()
}
}
impl From<Components> for Vec<Component> {
fn from(components: Components) -> Self {
components.inner.into_vec()
}
}
impl From<Vec<Component>> for Components {
fn from(components: Vec<Component>) -> Self {
Self {
inner: ComponentsInner::from_vec(components),
}
}
}
impl std::ops::Deref for Components {
type Target = [Component];
fn deref(&self) -> &Self::Target {
self.list()
}
}
impl std::ops::DerefMut for Components {
fn deref_mut(&mut self) -> &mut Self::Target {
self.list_mut()
}
}
impl<'a> IntoIterator for &'a Components {
type Item = &'a Component;
type IntoIter = std::slice::Iter<'a, Component>;
fn into_iter(self) -> Self::IntoIter {
self.list().iter()
}
}
impl<'a> IntoIterator for &'a mut Components {
type Item = &'a mut Component;
type IntoIter = std::slice::IterMut<'a, Component>;
fn into_iter(self) -> Self::IntoIter {
self.list_mut().iter_mut()
}
}
impl Components {
/// Creates a new empty [`Components`][crate::Components] type.
///
/// If you want it to be filled directly, take a look at
/// [`Components::new_with_refreshed_list`].
///
/// ```no_run
/// use sysinfo::Components;
///
/// let mut components = Components::new();
/// components.refresh_list();
/// for component in &components {
/// println!("{component:?}");
/// }
/// ```
pub fn new() -> Self {
Self {
inner: ComponentsInner::new(),
}
}
/// Creates a new [`Components`][crate::Components] type with the user list
/// loaded. It is a combination of [`Components::new`] and
/// [`Components::refresh_list`].
///
/// ```no_run
/// use sysinfo::Components;
///
/// let mut components = Components::new_with_refreshed_list();
/// for component in components.list() {
/// println!("{component:?}");
/// }
/// ```
pub fn new_with_refreshed_list() -> Self {
let mut components = Self::new();
components.refresh_list();
components
}
/// Returns the components list.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let components = Components::new_with_refreshed_list();
/// for component in components.list() {
/// println!("{component:?}");
/// }
/// ```
pub fn list(&self) -> &[Component] {
self.inner.list()
}
/// Returns the components list.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let mut components = Components::new_with_refreshed_list();
/// for component in components.list_mut() {
/// component.refresh();
/// println!("{component:?}");
/// }
/// ```
pub fn list_mut(&mut self) -> &mut [Component] {
self.inner.list_mut()
}
/// Refreshes the listed components' information.
///
/// ⚠️ If a component is added or removed, this method won't take it into account. Use
/// [`Components::refresh_list`] instead.
///
/// ⚠️ If you didn't call [`Components::refresh_list`] beforehand, this method will do
/// nothing as the component list will be empty.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let mut components = Components::new_with_refreshed_list();
/// // We wait some time...?
/// components.refresh();
/// ```
pub fn refresh(&mut self) {
#[cfg(all(
feature = "multithread",
not(feature = "unknown-ci"),
not(all(target_os = "macos", feature = "apple-sandbox")),
))]
use rayon::iter::ParallelIterator;
into_iter_mut(self.list_mut()).for_each(|component| component.refresh());
}
/// The component list will be emptied then completely recomputed.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let mut components = Components::new();
/// components.refresh_list();
/// ```
pub fn refresh_list(&mut self) {
self.inner.refresh_list()
}
}
/// Getting a component temperature information.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let components = Components::new_with_refreshed_list();
/// for component in &components {
/// println!("{} {}°C", component.label(), component.temperature());
/// }
/// ```
pub struct Component {
pub(crate) inner: ComponentInner,
}
impl Component {
/// Returns the temperature of the component (in celsius degree).
///
/// ## Linux
///
/// Returns `f32::NAN` if it failed to retrieve it.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let components = Components::new_with_refreshed_list();
/// for component in &components {
/// println!("{}°C", component.temperature());
/// }
/// ```
pub fn temperature(&self) -> f32 {
self.inner.temperature()
}
/// Returns the maximum temperature of the component (in celsius degree).
///
/// Note: if `temperature` is higher than the current `max`,
/// `max` value will be updated on refresh.
///
/// ## Linux
///
/// May be computed by `sysinfo` from kernel.
/// Returns `f32::NAN` if it failed to retrieve it.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let components = Components::new_with_refreshed_list();
/// for component in &components {
/// println!("{}°C", component.max());
/// }
/// ```
pub fn max(&self) -> f32 {
self.inner.max()
}
/// Returns the highest temperature before the component halts (in celsius degree).
///
/// ## Linux
///
/// Critical threshold defined by chip or kernel.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let components = Components::new_with_refreshed_list();
/// for component in &components {
/// println!("{:?}°C", component.critical());
/// }
/// ```
pub fn critical(&self) -> Option<f32> {
self.inner.critical()
}
/// Returns the label of the component.
///
/// ## Linux
///
/// Since components information is retrieved thanks to `hwmon`,
/// the labels are generated as follows.
/// Note: it may change and it was inspired by `sensors` own formatting.
///
/// | name | label | device_model | id_sensor | Computed label by `sysinfo` |
/// |---------|--------|------------|----------|----------------------|
/// | ✓ | ✓ | ✓ | ✓ | `"{name} {label} {device_model} temp{id}"` |
/// | ✓ | ✓ | ✗ | ✓ | `"{name} {label} {id}"` |
/// | ✓ | ✗ | ✓ | ✓ | `"{name} {device_model}"` |
/// | ✓ | ✗ | ✗ | ✓ | `"{name} temp{id}"` |
///
/// ```no_run
/// use sysinfo::Components;
///
/// let components = Components::new_with_refreshed_list();
/// for component in &components {
/// println!("{}", component.label());
/// }
/// ```
pub fn label(&self) -> &str {
self.inner.label()
}
/// Refreshes component.
///
/// ```no_run
/// use sysinfo::Components;
///
/// let mut components = Components::new_with_refreshed_list();
/// for component in components.iter_mut() {
/// component.refresh();
/// }
/// ```
pub fn refresh(&mut self) {
self.inner.refresh()
}
}
/// 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::new().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.
/// s.refresh_cpu();
///
/// 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::new().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.
/// s.refresh_cpu();
///
/// 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::new().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::new().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::new().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::new().with_cpu(CpuRefreshKind::everything()),
/// );
/// for cpu in s.cpus() {
/// println!("{}", cpu.frequency());
/// }
/// ```
pub fn frequency(&self) -> u64 {
self.inner.frequency()
}
}