1.5 Running a Simple DTrace Program

Using a text editor, create a new file called hello.d and type in this D program:

Example 1.1 hello.d: A simple D program that uses the BEGIN probe

/* hello.d -- A simple D program that uses the BEGIN probe */

  /* This is a C-style comment */
  trace("hello, world");

A D program consists of a series of clauses, where each clause describes one or more probes to enable, and an optional set of actions to perform when the probe fires. The actions are listed as a series of statements enclosed in braces {} following the probe name. Each statement ends with a semicolon (;). The function trace tells DTrace to record the specified argument, the string ”hello, world”, when the BEGIN probe fires, and then print it out. The function exit() tells DTrace to cease tracing and exit the dtrace command.

The full name of the BEGIN probe is dtrace:::BEGIN. DTrace provides three probes: dtrace:::BEGIN, dtrace:::END, and dtrace:::ERROR. As these probe names are unique to the dtrace provider, we can shorten their names to BEGIN, END, and ERROR.

After you have saved your program, you can run it by using the dtrace command with the -s option to specify the name of the file that contains the D program. Type the following command:

# dtrace -s hello.d
dtrace: script 'hello.d' matched 1 probe
CPU     ID                    FUNCTION:NAME
  0      1                           :BEGIN   hello, world   

DTrace interprets and runs the script. You will notice that, in addition to the string "hello,world", the default behavior of DTrace is to display information about the CPU on which the script was running when a probe fired, the ID of the probe, the name of the function that contains the probe, and the name of the probe itself. The function name is displayed as blank for BEGIN as DTrace provides this probe.

You can suppress the probe information in a number of different ways, for example, by specifying the -q option:

# dtrace -q -s hello.d
hello, world

The next chapter shows how you can use DTrace to explore different aspects of what is happening in the operating system.