i am describing an example.hope this will be helpful for you.
First of all, you need to create a simulator object. This is done with the command
set ns [new Simulator]
Now we open a file for writing that is going to be used for the nam trace data.
set nf [open out.nam w]
$ns namtrace-all $nf
The first line opens the file 'out.nam' for writing and gives it the file handle 'nf'. In the second line we tell the simulator object that we created above to write all simulation data that is going to be relevant for nam into this file.
The next step is to add a 'finish' procedure that closes the trace file and starts nam.
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
You don't really have to understand all of the above code yet. It will get clearer to you once you see what the code does.
The next line tells the simulator object to execute the 'finish' procedure after 5.0 seconds of simulation time.
$ns at 5.0 "finish"
You probably understand what this line does just by looking at it. ns provides you with a very simple way to schedule events with the 'at' command.