2.6.1 例: システムでのアクティビティをレポートするprocプローブの使用(activity.d)

次の例のDプログラムactivity.dでは、procプローブを使用してシステムのfork()およびexec()アクティビティをレポートします。

#pragma D option quiet

/* activity.d -- Record fork() and exec() activity */

proc::_do_fork:create
{
  /* Extract PID of child process from the psinfo_t pointed to by args[0] */
  childpid = args[0]->pr_pid;

  time[childpid] = timestamp;
  p_pid[childpid] = pid; /* Current process ID (parent PID of new child) */
  p_name[childpid] = execname; /* Parent command name */
  p_exec[childpid] = ""; /* Child has not yet been exec'ed */ 
}

proc::do_execveat_common:exec
/p_pid[pid] != 0/
{
  p_exec[pid] = args[0]; /* Child process path name */
}

proc::do_exit:exit
/p_pid[pid] != 0 &&  p_exec[pid] != ""/ 
{
  printf("%s (%d) executed %s (%d) for %d microseconds\n",
    p_name[pid], p_pid[pid], p_exec[pid], pid, (timestamp - time[pid])/1000);
}

proc::do_exit:exit
/p_pid[pid] != 0 &&  p_exec[pid] == ""/
{
  printf("%s (%d) forked itself (as %d) for %d microseconds\n",
    p_name[pid], p_pid[pid], pid, (timestamp - time[pid])/1000);
}  

この例では、#pragma D option quiet文の効果は、コマンドラインで-q オプションを指定した場合と同じです。

fork()に続く子プロセス(childpid)のプロセスIDは、args[0]プローブ引数によって示されるpsinfo_tデータ構造のpr_pid メンバーを調べることで決定されます。 procプローブへの引数の詳細は、Oracle® Linux: DTraceガイドprocプロバイダを参照してください。

プログラムでは、子プロセスIDの値を使用して、p_pid[childpid]などのグローバルに一意の連想配列エントリを初期化します。

注意

連想配列 は、キーと値を関連付けるという点で通常の配列に似ていますが、キーの型は任意で、整数である必要はありません。

プログラムを実行すると、ssh コマンドを使用して別のターミナル・ウィンドウから同じシステムにアクセスする場合と同様の出力が表示されます。 この新しいターミナル・ウィンドウから別のプログラムの実行を試みて、追加の出力を生成する場合があります:

# dtrace -s activity.d 
sshd (3966) forked itself (as 3967) for 3667020 microseconds
bash (3971) forked itself (as 3972) for 1718 microseconds
bash (3973) executed /usr/bin/hostname (3974) for 1169 microseconds
grepconf.sh (3975) forked itself (as 3976) for 1333 microseconds
bash (3977) forked itself (as 3978) for 967 microseconds
bash (3977) executed /usr/bin/tput (3979) for 1355 microseconds
bash (3980) executed /usr/bin/dircolors (3981) for 1212 microseconds
sshd (3966) executed /usr/sbin/unix_chkpwd (3968) for 31444 microseconds
sshd (3966) executed /usr/sbin/unix_chkpwd (3969) for 1653 microseconds
bash (3970) forked itself (as 3971) for 2411 microseconds
bash (3970) forked itself (as 3973) for 1830 microseconds
bash (3970) executed /usr/libexec/grepconf.sh (3975) for 3696 microseconds
bash (3970) forked itself (as 3977) for 3273 microseconds
bash (3970) forked itself (as 3980) for 1928 microseconds
bash (3970) executed /usr/bin/grep (3982) for 1570 microseconds
^C