1.5.1 Example: Simple D Program That Uses the BEGIN Probe (hello.d)

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

BEGIN
{
  /* This is a C-style comment */
  trace("hello, world");
  exit(0);
}

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 (;).

In this example, the function trace directs 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. Because these probe names are unique to the dtrace provider, their names can be shortened to BEGIN, END, and ERROR.

When you have saved your program, you can run it by using the dtrace command with the -s option, which specifies the name of the file that contains the D program:

# 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