• Daniel Xu's avatar
    Terminate bpftrace when traced PID terminates · 54909d3e
    Daniel Xu authored
    If the user provides a specific PID to trace, it doesn't really make
    sense to keep running if the tracee terminates. This patch makes
    bpftrace exit cleanly if the tracee terminates.
    
    I spent quite a bit of time thinking about the generic problem of
    figuring out when an arbitrary pid terminates. After some experiments,
    here is what I've learned:
    * wait(2) and waitpid(2) can only wait on child processes (duh)
    * epoll(2) does not support procfs (or other pseudo filesystems)
    * inotify does not support procfs either b/c procfs changes are not made
    through the filesystem (by another userspace entity)
    * ptrace with PTRACE_SEIZE might work but might have extra overhead on
    the tracee
    * the netlink interface for process state changes seems a bit overkill
    * the only sane solution (AFAICT) is to poll /proc/PID/ for changes
    
    Thus, I've made some minor changes to the main event loop to support
    polling procfs.
    
    Test Plan:
    Make sure non-pid-specific tracing still works:
    ```
    $ sudo ./build/src/bpftrace -e 'uretprobe:/bin/bash:readline { printf("read a line\n"); }'
    [sudo] password for dlxu:
    Attaching 1 probe...
    read a line
    read a line
    read a line
    read a line
    read a line
    read a line
    read a line
    read a line
    ^C
    
    ```
    
    Verify pid-specific tracing (ie usdt) exits on tracee termination:
    ```
    // in window 1
    $ ./python -q
    
    // in window 2
    $ sudo ~/dev/bpftrace/build/src/bpftrace -p $(pidof python) -e 'usdt:/home/dlxu/dev/cpython/python:function__entry { printf("%s %s\n", str(arg0), str(arg1)) }'
    [sudo] password for dlxu:
    Attaching 1 probe...
    <stdin> <module>
    
    // in window 1
    >>> print('wow')
    wow
    >>>
    
    // verify bpftrace has exited in window 2
    
    ```
    54909d3e
bpftrace.h 4.07 KB