Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

How to use Valgrind to track file descriptors

January 9, 2023
Mark Wielaard
Related topics:
Secure Coding
Related products:
Red Hat Enterprise Linux

Share:

    Valgrind is normally associated with finding memory issues and tracking memory use of programs. But it can also track other resources like file descriptors, including where in your program they were originally opened.

    File descriptors

    A file descriptor is a positive integer number representing resources that can do input or output. Naturally, they can represent files that your program opens, but also network sockets and pipes between programs. Also, file descriptors can be created for monitoring timers, signals, and process ids.

    File descriptors are, by default, a limited resource. ulimit -n will show you what the default number of file descriptors that a program can open. A program can normally have only 1024 file descriptors open. Although this number can be increased (also using ulimit -n), you might still want to make sure you don't keep file descriptors open unnecessarily.

    As long as a file descriptor is open, the resources associated with it cannot be released. For example, a file cannot be deleted from the disk if a program is still reading it, or a network port will be kept open. Also, open file descriptors are inherited by any program created by execve (unless it was opened with the O_CLOEXEC flag).

    Valgrind --track-fds=yes

    So forgetting to close a file descriptor when it is no longer needed wastes resources and might indicate a logical error in your program. Just like a memory leak, you can leak file descriptors by forgetting to close them when you are done with them. Valgrind can help you track down when that happens. Valgrind tracks all system calls that create or close/destroy file descriptors. So at the end of your program, it can show you which were opened but never closed.

    Take, for example, this trivial program that reads a preferences file but forgets to close it after it has read all program settings:

    
    #include <stdio.h>
    
    int main ()
    
    {
      /* Read preferences.  */
    
      FILE *prefs = fopen ("myprefs", "r");
    
      /* Parse preferences.  Forget to fclose prefs.  */
    
      return 0;
    }
    

    Let's compile this and make sure the myprefs file exists:

    $ gcc -g -o leaky leaky.c
    
    $ touch myprefs

    Now when running this under valgrind with --track-fds=yes (which works with any valgrind tool, including the none tool, in case you aren't interested in any other memory tracking reports), it will point out that a file descriptor is still open in your program and tell you where it was originally opened:

    $ valgrind -q --tool=none --track-fds=yes ./leaky
    
    ==3283== FILE DESCRIPTORS: 4 open (3 std) at exit.
    
    ==3283== Open file descriptor 3: myprefs
    
    ==3283==    at 0x4953628: open (open64.c:41)
    
    ==3283==    by 0x48D73D5: _IO_file_open (fileops.c:188)
    
    ==3283==    by 0x48D759A: _IO_file_fopen@@GLIBC_2.2.5 (fileops.c:280)
    
    ==3283==    by 0x48CB88C: __fopen_internal (iofopen.c:75)
    
    ==3283==    by 0x40113C: main (leaky.c:6)

    You see that the code on line 6 was responsible for opening the file descriptor for myprefs, but the stacktrace shows it was actually created inside the glibc library.

    Also note that valgrind reports 4 open file descriptors (3 std). There are three standard file descriptors, stdin (0), stdout (1), and stderr (2), for reading from standard input, writing to standard output, or standard error. The standard 3 file descriptors are normally not reported because programs usually don't close and/or reassign these file descriptors.

    If you do want to see a report on the standard file descriptors, you can run valgrind with --track-fds=all (this is a new option since valgrind 3.17.0):

    
    $ valgrind -q --tool=none --track-fds=all ./leaky
    
    ==3292== FILE DESCRIPTORS: 4 open (3 std) at exit.
    
    ==3292== Open file descriptor 3: myprefs
    
    ==3292==    at 0x4953628: open (open64.c:41)
    
    ==3292==    by 0x48D73D5: _IO_file_open (fileops.c:188)
    
    ==3292==    by 0x48D759A: _IO_file_fopen@@GLIBC_2.2.5 (fileops.c:280)
    
    ==3292==    by 0x48CB88C: __fopen_internal (iofopen.c:75)
    
    ==3292==    by 0x40113C: main (leaky.c:6)
    
    ==3292== 
    
    ==3292== Open file descriptor 2: /dev/pts/1
    
    ==3292==    
    
    ==3292== 
    
    ==3292== Open file descriptor 1: /dev/pts/1
    
    ==3292==    
    
    ==3292== 
    
    ==3292== Open file descriptor 0: /dev/pts/1
    
    ==3292==    
    

    Interactive tracking with vgdb or gdb

    Knowing which file descriptors are still open when the program finishes is very useful to see whether you can close those and free the resources associated with it. But it is also useful to know which file descriptors are open during the runtime of the program. Sometimes the usage of a library might open unexpected file descriptors. Or file descriptors might be kept open for longer than necessary.

    To monitor a program running under valgrind you can use the vgdb utility. vgdb can be used as standalone utility or in combination with gdb. As a standalone utility, it can query a running valgrind process to see which file descriptors are open.

    For example, if we are running our favorite editor with valgrind --track-fds=yes emacs, then we can interactively query the current open file descriptors (and where they were opened) by running:

    
    $ vgdb v.info open_fds
    
    sending command v.info open_fds to pid 4472
    
    ==4472== FILE DESCRIPTORS: 6 open (3 std) .
    
    ==4472== Open AF_INET socket 5: xxx.xxx.xxx.xxx:60770 <-> yyy.yyy.yyy.yyy:443
    
    ==4472==    at 0x724C64B: socket (syscall-template.S:120)
    
    ==4472==    by 0x586709: connect_network_socket.lto_priv.0 (process.c:3366)
    
    ==4472==    by 0x5C58B4: wait_reading_process_output (process.c:5249)
    
    ==4472==    by 0x425D28: sit_for (dispnew.c:6161)
    
    ==4472==    by 0x4BA2AD: read_char (keyboard.c:2800)
    
    ==4472==    by 0x4C1AE6: read_key_sequence.lto_priv.0 (keyboard.c:9635)
    
    ==4472==    by 0x4B41CA: command_loop_1.lto_priv.0 (keyboard.c:1392)
    
    ==4472==    by 0x530746: internal_condition_case (eval.c:1450)
    
    ==4472==    by 0x4AFDAD: command_loop_2 (keyboard.c:1133)
    
    ==4472==    by 0x530688: internal_catch (eval.c:1181)
    
    ==4472==    by 0x4B1A88: command_loop.lto_priv.0 (keyboard.c:1111)
    
    ==4472==    by 0x5C35CC: recursive_edit_1.isra.0 (keyboard.c:720)
    
    ==4472== 
    
    ==4472== Open file descriptor 4: /dev/tty
    
    ==4472==    at 0x723A7A6: openat (openat64.c:39)
    
    ==4472==    by 0x4A0152: init_tty (fcntl2.h:129)
    
    ==4472==    by 0x42917C: init_display_interactive.lto_priv.0 (dispnew.c:6492)
    
    ==4472==    by 0x41D166: main (dispnew.c:6560)
    
    ==4472== 
    
    ==4472== Open file descriptor 3:
    
    ==4472==    at 0x724B99B: timerfd_create (syscall-template.S:120)
    
    ==4472==    by 0x41E9CE: main (atimer.c:584)
    

    Here you see that emacs at that time had 3 (extra) file descriptors open, one for a timer, one for a terminal display, and one for a network socket. The IP addresses are obscured in the above output for a buffer that was using eww (the Emacs Web Wowser) to load a web page.

    Note that if there are multiple processes running under valgrind (for example, because you used valgrind --trace-children=yes), then you have to tell vgdb which process to query using --pid=xxxx.

    To have more control over when exactly to show the known open file descriptors, you can also use vgdb together with valgrind just like how you Debug memory errors with Valgrind and GDB.

    Using the valgrind option --vgdb-error=0 and the gdb target remote | vgdb command, as the above article describes, you can interrupt, step through, or set breakpoints in your program where you want to see which file descriptors are open. Then you can use the gdb monitor command to query valgrind. Here is an example running the bash shell under valgrind and gdb:

    
    (gdb) monitor v.info open_fds
    
    ==5338== FILE DESCRIPTORS: 4 open (3 std) .
    
    ==5338== Open file descriptor 255: /dev/pts/3
    
    ==5338==    at 0x499A0EB: dup2 (syscall-template.S:120)
    
    ==5338==    by 0x147FEA: move_to_high_fd (general.c:661)
    
    ==5338==    by 0x16DC23: initialize_job_control (jobs.c:4412)
    
    ==5338==    by 0x13CAE6: shell_initialize (shell.c:1994)
    
    ==5338==    by 0x139F78: main (shell.c:590)
    

    Wrap up

    Valgrind cannot just track memory use but also file descriptors used by your program. File descriptors are finite resources that should be closed when the program is done with the underlying resource to reclaim (kernel) memory or device resources, which is important for long-running processes.

    Valgrind using --track-fds=yes can show you which file descriptors were never closed by your program. And in combination with vgdb and gdb, it can help you show which file descriptors are open at various stages of your program and where those file descriptors were originally opened.

    Last updated: August 14, 2023

    Related Posts

    • Valgrind Memcheck: Different ways to lose your memory

    • Use Valgrind Memcheck with a custom memory manager

    • Using Valgrind's --trace-flags option

    • Memory error checking in C and C++: Comparing Sanitizers and Valgrind

    Recent Posts

    • More Essential AI tutorials for Node.js Developers

    • How to run a fraud detection AI model on RHEL CVMs

    • How we use software provenance at Red Hat

    • Alternatives to creating bootc images from scratch

    • How to update OpenStack Services on OpenShift

    What’s up next?

    Ready to level up your Linux knowledge? Our Intermediate Linux Cheat Sheet presents a collection of Linux commands and executables for developers and system administrators who want to move beyond the basics.

    Get the cheat sheet
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue