Count the number of open file descriptors.
()
| 653 | |
| 654 | |
| 655 | def fd_count(): |
| 656 | """Count the number of open file descriptors. |
| 657 | """ |
| 658 | if sys.platform.startswith(('linux', 'android', 'freebsd', 'emscripten')): |
| 659 | fd_path = "/proc/self/fd" |
| 660 | elif support.is_apple: |
| 661 | fd_path = "/dev/fd" |
| 662 | else: |
| 663 | fd_path = None |
| 664 | |
| 665 | if fd_path is not None: |
| 666 | try: |
| 667 | names = os.listdir(fd_path) |
| 668 | # Subtract one because listdir() internally opens a file |
| 669 | # descriptor to list the content of the directory. |
| 670 | return len(names) - 1 |
| 671 | except FileNotFoundError: |
| 672 | pass |
| 673 | |
| 674 | MAXFD = 256 |
| 675 | if hasattr(os, 'sysconf'): |
| 676 | try: |
| 677 | MAXFD = os.sysconf("SC_OPEN_MAX") |
| 678 | except OSError: |
| 679 | pass |
| 680 | |
| 681 | old_modes = None |
| 682 | if sys.platform == 'win32': |
| 683 | # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process |
| 684 | # on invalid file descriptor if Python is compiled in debug mode |
| 685 | try: |
| 686 | import msvcrt |
| 687 | msvcrt.CrtSetReportMode |
| 688 | except (AttributeError, ImportError): |
| 689 | # no msvcrt or a release build |
| 690 | pass |
| 691 | else: |
| 692 | old_modes = {} |
| 693 | for report_type in (msvcrt.CRT_WARN, |
| 694 | msvcrt.CRT_ERROR, |
| 695 | msvcrt.CRT_ASSERT): |
| 696 | old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, |
| 697 | 0) |
| 698 | |
| 699 | try: |
| 700 | count = 0 |
| 701 | for fd in range(MAXFD): |
| 702 | try: |
| 703 | # Prefer dup() over fstat(). fstat() can require input/output |
| 704 | # whereas dup() doesn't. |
| 705 | fd2 = os.dup(fd) |
| 706 | except OSError as e: |
| 707 | if e.errno != errno.EBADF: |
| 708 | raise |
| 709 | else: |
| 710 | os.close(fd2) |
| 711 | count += 1 |
| 712 | finally: |
searching dependent graphs…