Search code examples
macosparent-childdtracemachxnu

Dtrace print parent process command


I'd like to have a script that for each new running process, prints its starting command, as well as its parent process.

i'm using the following probes :

proc::posix_spawn:exec-success,proc::__mac_execve:exec-success

From within the script body, command line string is built from curproc->p_dtrace_argv.

parent pid (ppid) is also available, but so far I haven't managed to figure out how to extract the parent process name (preferably full name that can be taken from parent argv[0]).


Solution

  • You can capture the execname of the process prior to the call to exec() in the proc:::exec probe. That will be the name of the executable that called fork() and will match the execname of the parent process.

    I tested this on a Solaris 11 installation:

    #!/usr/sbin/dtrace -s
    
    proc:::exec
    {
        self->pexecname = execname;
    }
    
    proc:::exec-success
    / self->pexecname != 0 /
    {
        printf( "execname: %s, parent execname: %s", execname, self->pexecname );
        self->pexecname = 0;
    }
    

    It produced the following output:

    dtrace: script './exec.d' matched 2 probes
     CPU     ID                    FUNCTION:NAME
       6  12486         exec_common:exec-success execname: utmp_update, parent execname: gnome-pty-helper
      14  12486         exec_common:exec-success execname: bash, parent execname: gnome-terminal
      15  12486         exec_common:exec-success execname: ls, parent execname: bash
    

    Updated per comments:

    #!/usr/sbin/dtrace -s
    
    proc:::exec
    {
        self->pexecname = execname;
        self->parent_args = (build parent args off curproc here)
    }
    
    proc:::exec-success
    / self->pexecname != 0 /
    {
        printf( "execname: %s, parent execname: %s", execname, self->pexecname );
        self->pexecname = 0;
        self->parent_args = 0;
    }
    
    proc:::exec-failure
    / self->pexecname != 0 /
    {
        self->pexecname = 0;
        self->parent_args = 0;
    }