Strace
Содержание:
- Introduction
- NOTES
- Save traced command output to a file
- Notes
- NOTES top
- Notes
- Технические детали
- Setuid Installation
- EXAMPLES top
- Примеры использования tr
- Examples
- Утилита Traceroute
- PARAMETER PACKS top
- Purpose of tracepoints¶
- COLOPHON top
- Trace a particular system call with strace
- Description
- Trace network calls.
- FILTER EXPRESSIONS top
- Обзор nweb
- Примеры трассировки сети в Linux
- EXPRESSIONS top
- Examples
- Notes
- Strace from the standpoint of a system administrator
- Basic usage
- COLOPHON top
Introduction
Strace is a utility that can trace system calls. If you’re wondering what system calls are, they are a
translation mechanism that provides interface between a process and the operating system (kernel). These calls
can be intercepted and read, allowing for a better understanding of what a process is trying to do at a given
runtime.
By hooking these calls, we can get a better understanding of how a process behaves, especially if it’s
misbehaving. The operating system functionality that allows tracing is called ptrace. Strace calls on ptrace
and reads the process behavior, reporting back.
Today, we will learn when to use strace, how to use it, how to interpret its output, how to glean errors from
the strace output, and solve problems quickly and efficiently.
Follow me.
NOTES
It is instructive to think about system call inputs and outputs
as data-flow across the user/kernel boundary. Because user-space
and kernel-space are separate and address-protected, it is
sometimes possible to make deductive inferences about process
behavior using inputs and outputs as propositions.
In some cases, a system call will differ from the documented behavior
or have a different name. For example, the
faccessat(2)
system call does not have
flags
argument, and the
setrlimit(2)
library function uses
prlimit64(2)
system call on modern (2.6.38+) kernels. These
discrepancies are normal but idiosyncratic characteristics of the
system call interface and are accounted for by C library wrapper
functions.
Some system calls have different names in different architectures and
personalities. In these cases, system call filtering and printing
uses the names that match corresponding
__NR_*
kernel macros of the tracee’s architecture and personality.
There are two exceptions from this general rule:
arm_fadvise64_64(2)
ARM syscall and
xtensa_fadvise64_64(2)
Xtensa syscall are filtered and printed as
fadvise64_64(2).
On x32, syscalls that are intended to be used by 64-bit processes and not x32
ones (for example,
readv(2),
that has syscall number 19 on x86_64, with its x32 counterpart has syscall
number 515), but called with
__X32_SYSCALL_BIT
flag being set, are designated with
#64
suffix.
On some platforms a process that is attached to with the
-p
option may observe a spurious
EINTR
return from the current system call that is not restartable.
(Ideally, all system calls should be restarted on
strace
attach, making the attach invisible
to the traced process, but a few system calls aren’t.
Arguably, every instance of such behavior is a kernel bug.)
This may have an unpredictable effect on the process
if the process takes no action to restart the system call.
As
strace
executes the specified
command
directly and does not employ a shell for that, scripts without shebang
that usually run just fine when invoked by shell fail to execute with
ENOEXEC
error.
It is advisable to manually supply a shell as a
command
with the script as its argument.
Save traced command output to a file
strace -o <file_to_save> <command>
Example:
root@linuxnix:/home/surendra# strace -o pwd.txt pwd /home/surendra
In our next post, we will see ltrace and mtrace commands.
Post Views:
24,223
The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.
Latest posts by Surendra Anne
- Docker: How to copy files to/from docker container — June 30, 2020
- Anisble: ERROR! unexpected parameter type in action: Fix — June 29, 2020
- FREE: JOIN OUR DEVOPS TELEGRAM GROUPS — August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) — August 27, 2018
- How to use ohai/chef-shell to get node attributes — July 19, 2018
Notes
It is a pity that so much tracing clutter is produced by systems employing shared libraries.
It is instructive to think about system call inputs and outputs as data-flow across the user/kernel boundary. Because user-space and kernel-space are
separate and address-protected, it is sometimes possible to make deductive inferences about process behavior using inputs and outputs as propositions.
In some cases, a system call will differ from the documented behavior or have a different name. For example, on System V-derived systems the true
time(2) system call does not take an argument and the stat function is called xstat and takes an extra leading argument. These
discrepancies are normal but idiosyncratic characteristics of the system call interface and are accounted for by C library wrapper functions.
On some platforms a process that has a system call trace applied to it with the -p option will receive a SIGSTOP . This signal
may interrupt a system call that is not restartable. This may have an unpredictable effect on the process if the process takes no action to restart the system
call.
NOTES top
In normal usage, mtrace() is called once at the start of execution of
a program, and muntrace() is never called.
The tracing output produced after a call to mtrace() is textual, but
not designed to be human readable. The GNU C library provides a Perl
script, mtrace(1), that interprets the trace log and produces human-
readable output. For best results, the traced program should be
compiled with debugging enabled, so that line-number information is
recorded in the executable.
The tracing performed by mtrace() incurs a performance penalty (if
MALLOC_TRACE points to a valid, writable pathname).
Notes
To speed up work, normally several probes are sent simultaneously. On the other hand, it creates a «storm of packages», especially in the reply direction.
Routers can throttle the rate of icmp responses, and some of replies can be lost. To avoid this, decrease the number of simultaneous probes, or even set it to
1 (like in initial traceroute implementation), i.e. -N 1
The final (target) host can drop some of the simultaneous probes, and might even answer only the latest ones. It can lead to extra «looks like expired» hops
near the final hop. We use a smart algorithm to auto-detect such a situation, but if it cannot help in your case, just use -N 1 too.
For even greater stability you can slow down the program’s work by -z option, for example use -z 0.5 for half-second pause between probes.
If some hops report nothing for every method, the last chance to obtain something is to use ping -R command (IPv4, and for nearest 8 hops
only).
Технические детали
Особенности
GDB предлагает обширные средства для слежения и контроля за выполнением компьютерных программ. Пользователь может изменять внутренние переменные программ и даже вызывать функции независимо от обычного поведения программы. GDB может отлаживать исполняемые файлы в формате a.out, COFF (в том числе исполняемые файлы Windows), ECOFF, XCOFF, ELF, , использовать отладочную информацию в форматах stabs, COFF, ECOFF, DWARF, DWARF2. Наибольшие возможности отладки предоставляет формат DWARF2.
GDB активно развивается. Например, в версии 7.0 добавлена поддержка «обратимой отладки», позволяющей отмотать назад процесс выполнения, чтобы посмотреть, что произошло. Также в версии 7.0 была добавлена поддержка скриптинга на Python’е.
Для работы с GDB были созданы и другие инструменты отладки, например, датчики утечки памяти[].
Мультиплатформенность и поддержка встроенных систем
GDB может быть скомпилирован для поддержки приложений для нескольких целевых платформ и переключаться между ними во время отладочной сессии. Процессоры, поддерживаемые GDB (): Alpha, ARM, H8/300, System/370, System/390, x86 и x86-64, IA-64 (Itanium), Motorola 68000, MIPS, PA-RISC, PowerPC, SuperH, SPARC, VAX, A29K, ARC, AVR, CRIS, D10V, D30V, FR-30, FR-V, Intel i960, M32R, 68HC11, Motorola 88000, MCORE, MN10200, MN10300, NS32K, Stormy16, V850, С-SKY и Z8000 (более новые выпуски не будут, вероятно, поддерживать некоторые из них.)
Целевые платформы, на которых GDB не может быть запущен, в частности, встроенные системы, могут поддерживаться с помощью встроенного симулятора (процессоры ARM, AVR), либо приложения для них могут быть скомпилированы со специальными подпрограммами, обеспечивающими удаленную отладку под управлением GDB, запущенном на компьютере разработчика. Входным файлом для отладки, как правило, используется не прошиваемый двоичный файл, а файл в одном из поддерживающих отладочную информацию форматов, в первую очередь ELF, из которого впоследствии с помощью специальных утилит извлекается двоичный код для прошивки.
Удаленная отладка
При удаленной отладке GDB запускается на одной машине, а отлаживаемая программа запускается на другой. Связь осуществляется по специальному протоколу через последовательный порт или TCP/IP. Протокол взаимодействия с отладчиком специфичен для GDB, но исходные коды необходимых подпрограмм включены в архив отладчика. Как альтернатива, на целевой платформе может быть запущена использующая тот же протокол программа gdbserver из состава пакета GDB, исполняющая низкоуровневые функции вроде установки точек останова и доступа к регистрам и памяти.
Этот же режим используется для взаимодействия со встроенным отладчиком ядра Linux KGDB. С его помощью разработчик может отлаживать ядро как обычную программу: устанавливать точки останова, делать пошаговое исполнение кода, просматривать переменные. Встроенный отладчик требует наличия двух машин, соединенных через Ethernet или последовательный кабель, на одном из которых запущен GDB, на другом — отлаживаемое ядро.
Пользовательский интерфейс
В соответствии с идеологией ведущих разработчиков FSF, GDB вместо собственного графического пользовательского интерфейса предоставляет возможность подключения к внешним IDE, управляющим графическим оболочкам либо использовать стандартный консольный текстовый интерфейс. Для сопряжения с внешними программами можно использовать язык текстовой строки (как это было сделано в первых версиях оболочки DDD), текстовый язык управления либо интерфейс для языка Python.
Были созданы такие интерфейсы, как DDD, cgdb, GDBtk/Insight и «GUD mode» в Emacs. С GDB могут взаимодействовать такие IDE, как Code::Blocks, Qt Creator, KDevelop, Eclipse, NetBeans, Lazarus, Geany.
Примеры команд
| gdb program | произвести отладку программы «program» (из командной оболочки) |
|---|---|
| break main | установить точку остановки на main |
| run -v | запустить загруженную программу с параметром -v |
| bt | обратная трассировка (в случае аварийного завершения программы) |
| info registers | показать все регистры |
| disass $pc-32, $pc+32 | дизассемблировать код |
| disassemble main | дизассемблировать функцию main |
| set disassembly-flavor intel | отображать команды ассемблера в синтаксисе intel |
Setuid Installation
If strace is installed setuid to root then the invoking user will be able to attach to and trace processes owned by any user. In addition setuid and
setgid programs will be executed and traced with the correct effective privileges. Since only users trusted with full root privileges should be allowed to do
these things, it only makes sense to install strace as setuid to root when the users who can execute it are restricted to those users who have this
trust. For example, it makes sense to install a special version of strace with mode ‘rwsr-xr—‘, user root and group trace, where members
of the trace group are trusted users. If you do use this feature, please remember to install a non-setuid version of strace for ordinary lusers
to use.
EXAMPLES top
In the following, the first is the C prototype, and following that is
ltrace configuration line.
void func_charp_string(char str[]);
void func_charp_string(string);
enum e_foo {RED, GREEN, BLUE};
void func_enum(enum e_foo bar);
void func_enum(enum(RED,GREEN,BLUE));
- or -
typedef e_foo = enum(RED,GREEN,BLUE);
void func_enum(e_foo);
void func_arrayi(int arr[], int len);
void func_arrayi(array(int,arg2)*,int);
struct S1 {float f; char a; char b;};
struct S2 {char str6]; float f;};
struct S1 func_struct(int a, struct S2, double d);
struct(float,char,char) func_struct(int,
struct(string(array(char, 6)),float), double);
Примеры использования tr
1. Замена символов через аргументы
Программа по умолчанию работает со стандартным вводом/выводом.
Пример 1. Заменить все x на z.
Далее следует ввести строку и нажать Enter. Ниже будет выведен обработанный результат и представлена возможность повторного ввода.

Для выхода из программы нажмите Ctrl + D.
Пример 2. Удалить все буквы в нижнем регистре.

Пример 3. Уплотнить повторяющиеся буквы большого и малого регистров.

2. Работа с потоками
Команда tr может принимать на вход результат работы другой программы с использованием пайпа.
Пример 4. Вывести первые три строки файла /etc/passwd, заменив двоеточия (используемые в качестве разделителя данных) на пробелы.

Также можно использовать перенаправление потока ввода и вывода.
Пример 5. Заменить цифры IP-адреса файла addresses2 на буквы a, и результат записать в файл addresses3.

Examples
The following is an example of typical output of the command:
user@server:~$ strace ls
...
open(".", O_RDONLY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY|O_CLOEXEC) = 3
fstat64(3, {st_mode=S_IFDIR|0755, st_size=4096, ...}) =
fcntl64(3, F_GETFD) = 0x1 (flags FD_CLOEXEC)
getdents64(3, /* 18 entries */, 4096) = 496
getdents64(3, /* 0 entries */, 4096) =
close(3) =
fstat64(1, {st_mode=S_IFIFO|0600, st_size=, ...}) =
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, ) = 0xb7f2c000
write(1, "autofs\nbackups\ncache\nflexlm\ngames"..., 86autofsA
The above fragment is only a small part of the output of strace when run on the ‘ls’ command. It shows that the current working directory is opened, inspected and its contents retrieved. The resulting list of file names is written to standard output.
Утилита Traceroute
Перед тем как перейти к примерам работы с утилитой давайте рассмотрим ее синтаксис и основные опции. Синтаксис вызова очень прост:
$ traceroute опции адрес_узла
В качестве адреса может использоваться ip адрес или доменное имя. Рассмотрим основные опции:
- -4 или -6 — использовать ipv4 или ipv6 протокол;
- -I — использовать ICMP пакеты вместо UDP;
- -T — использовать TCP пакеты вместо UDP;
- -F — не фрагментировать пакеты;
- -f — указать TTL с которого нужно начать;
- -g — передавать пакет через указанный шлюз;
- -i — передавать пакет через указанный интерфейс;
- -m — максимальное количество узлов, через которые пройдет пакет;
- -q — количество пакетов, отправляемых за раз, по умолчанию три;
- -n — не узнавать доменные имена;
- -p — указать порт вместо порта по умолчанию;
- -w — установить время ожидания ответа от узла, по умолчанию полсекунды;
- -r — использовать другой роутер вместо того, что указанный в таблице маршрутизации;
- -z — минимальный интервал между пакетами;
- -U — использовать UDP с увеличением номера порта;
- -UL — использовать протокол UDPLITE;
- -D — использовать протокол DCCP;
- —mtu — указать размер пакета;
- -P — протокол, доступны такие значения: raw, dccp, udplite, udp, tcpconn, tcp, icmp.
Это не все опции утилиты, но все основные, которыми вы будете пользоваться. Дальше перейдем практике того, как выполняется трассировка сети Linux.
PARAMETER PACKS top
Sometimes the actual function prototype varies slightly depending on
the exact parameters given. For example, the number and types of
printf parameters are not known in advance, but ltrace might be able
to determine them in runtime. This feature has wider applicability,
but currently the only parameter pack that ltrace supports is printf-
style format string itself:
format When format is seen in the parameter list, the underlying
string argument is parsed, and GNU-style format specifiers are
used to determine what the following actual arguments are.
E.g. if the format string is "%s %d\n", it's as if the format
was replaced by string, string, int.
Purpose of tracepoints¶
A tracepoint placed in code provides a hook to call a function (probe)
that you can provide at runtime. A tracepoint can be “on” (a probe is
connected to it) or “off” (no probe is attached). When a tracepoint is
“off” it has no effect, except for adding a tiny time penalty
(checking a condition for a branch) and space penalty (adding a few
bytes for the function call at the end of the instrumented function
and adds a data structure in a separate section). When a tracepoint
is “on”, the function you provide is called each time the tracepoint
is executed, in the execution context of the caller. When the function
provided ends its execution, it returns to the caller (continuing from
the tracepoint site).
You can put tracepoints at important locations in the code. They are
lightweight hooks that can pass an arbitrary number of parameters,
which prototypes are described in a tracepoint declaration placed in a
header file.
COLOPHON top
This page is part of the ltrace (library call tracer) project.
Information about the project can be found at ⟨http://ltrace.org/⟩.
If you have a bug report for this manual page, see
⟨http://ltrace.org/⟩. This page was obtained from the project's
upstream Git repository ⟨https://github.com/dkogan/ltrace⟩ on
2020-08-13. (At that time, the date of the most recent commit that
was found in the repository was 2016-09-01.) If you discover any
rendering problems in this HTML version of the page, or you believe
there is a better or more up-to-date source for the page, or you have
corrections or improvements to the information in this COLOPHON
(which is not part of the original manual page), send a mail to
man-pages@man7.org
October 2012 ltrace.conf(5)
Pages that refer to this page:
ltrace(1)
Trace a particular system call with strace
The strace command can be used to filter out particular system call without the help of grep. Use -e to specify which system call you want to see.
strace -e <call-type> <command>
Example Output:
surendra@linuxnix:~/code/sh$ strace -e open pwd
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
/home/surendra/code/sh
+++ exited with 0 +++
Some of the frequently used system call options are
execve, access, open, read, and write fstat, getrlimit, getdents, ioctl and statfs. close and brk mmap and mprotect
Description
The blktrace utility extracts event traces from the kernel (via the relaying through the debug file system). Some background details concerning the
run-time behaviour of blktrace will help to understand some of the more arcane command line options:
- —
- blktrace receives data from the kernel in buffers passed up through the debug file system (relay). Each device being traced has a file created in the
mounted directory for the debugfs, which defaults to /sys/kernel/debug — this can be overridden with the -r command line argument. - —
- blktrace defaults to collecting all events that can be traced. To limit the events being captured, you can specify one or more filter masks via the
-a option.Alternatively, one may specify the entire mask utilising a hexadecimal value that is version-specific. (Requires understanding of the internal
representation of the filter mask.) - —
- As noted above, the events are passed up via a series of buffers stored into debugfs files. The size and number of buffers can be specified via the
-b and -n arguments respectively. - —
- blktrace stores the extracted data into files stored in the local directory. The format of the file names is (by default)
device.blktrace.cpu, where device is the base device name (e.g, if we are tracing /dev/sda, the base device name would be
sda); and cpu identifies a CPU for the event stream.The device portion of the event file name can be changed via the -o option.
- —
- blktrace may also be run concurrently with blkparse to produce live output — to do this specify -o — for blktrace.
- —
- The default behaviour for blktrace is to run forever until explicitly killed by the user (via a control-C, or sending SIGINT signal to the process via
invocation the kill (1) utility). Also you can specify a run-time duration for blktrace via the -w option — then blktrace will run for the
specified number of seconds, and then halt.
Trace network calls.
One of the system call option available is a network; We can use this to see if any network calls are happening or not.
Example:
root@linuxnix:/home/surendra# strace -e trace=network ifconfig
socket(PF_LOCAL, SOCK_DGRAM, 0) = 3
socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 4
socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP) = 5
docker0 Link encap:Ethernet HWaddr 02:42:5a:71:90:c8
inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
FILTER EXPRESSIONS top
Filter expression is a chain of glob- or regexp-based rules that are
used to pick symbols for tracing from libraries that the process
uses. Most of it is intuitive, so as an example, the following would
trace calls to malloc and free, except those done by libc:
-e malloc+free-@libc.so*
This reads: trace malloc and free, but don't trace anything that
comes from libc. Semi-formally, the syntax of the above example
looks approximately like this:
{[symbol_pattern][@library_pattern]}
Symbol_pattern is used to match symbol names, library_pattern to
match library SONAMEs. Both are implicitly globs, but can be regular
expressions as well (see below). The glob syntax supports meta-
characters * and ? and character classes, similarly to what basic
bash globs support. ^ and $ are recognized to mean, respectively,
start and end of given name.
Both symbol_pattern and library_pattern have to match the whole name.
If you want to match only part of the name, surround it with one or
two *'s as appropriate. The exception is if the pattern is not
mentioned at all, in which case it's as if the corresponding pattern
were *. (So malloc is really malloc@* and @libc.* is really
*@libc.*.)
In libraries that don't have an explicit SONAME, basename is taken
for SONAME. That holds for main binary as well: /bin/echo has an
implicit SONAME of echo. In addition to that, special library
pattern MAIN always matches symbols in the main binary and never a
library with actual SONAME MAIN (use e.g. ^MAIN or AIN for that).
If the symbol or library pattern is surrounded in slashes (/like
this/), then it is considered a regular expression instead. As a
shorthand, instead of writing /x/@/y/, you can write /x@y/.
If the library pattern starts with a slash, it is not a SONAME
expression, but a path expression, and is matched against the library
path name.
The first rule may lack a sign, in which case + is assumed. If, on
the other hand, the first rule has a - sign, it is as if there was
another rule @ in front of it, which has the effect of tracing
complement of given rule.
The above rules are used to construct the set of traced symbols.
Each candidate symbol is passed through the chain of above rules.
Initially, the symbol is unmarked. If it matches a + rule, it
becomes marked, if it matches a - rule, it becomes unmarked again.
If, after applying all rules, the symbol is marked, it will be
traced.
Обзор nweb
Далее потребуется что-либо более крупное и сложное, нежели простая UNIX-команда типа . Простой сервер Hypertext Transfer Protocol (HTTP), такой как nweb, прекрасно подойдет. HTTP-сервер слушает запросы Web-браузера, когда вы бороздите Интернет, и отправляет по этим запросам запрашиваемые объекты, такие как Web-страницы и графические файлы.
Потребуется скачать и установить nweb, написанный сотрудником IBM developerWorks Нигелем Гриффитсом (см. ссылку в разделе на статью Нигеля — «nweb: a tiny, safe Web server (static pages only)» (developerWorks, июнь 2004).)
После загрузки архива es-nweb.zip в папку $HOME/downloads необходимо набрать простые команды, выполняющие извлечение, компиляцию и запуск программы ():
Замечание. Предполагается, что программа будет компилироваться на рабочей станции с Linux. Если это не так, то необходимо прочесть справку nweb’а о деталях компилирования программы для других вариантов UNIX.
Листинг 2. Команды извлечения, компиляции и запуска nweb
$ cd src $ mkdir nweb $ cd nweb $ unzip $HOME/downloads/es-nweb.zip $ gcc -ggdb -O -DLINUX nweb.c -o nweb $ ./nweb 9090 $HOME/src/nweb &
Замечание. Опция в отличается от статьи Нигеля и дает команду компилятору GCC оптимизировать программу для отладки в отладчике GDB, который будет использоваться позже.
Далее нужно проверить, что nweb-сервер запущен, используя команду для отображения результатов проверки ().
Листинг 3. Команда ps
$ ps PID TTY TIME CMD 2913 pts/5 00:00:00 bash 4009 pts/5 00:00:00 nweb 4011 pts/5 00:00:00 ps
Наконец, нужно проверить, что nweb действительно запущен и все корректно, запустив Web-браузер на компьютере и набрав в адресной строке.
Использование strace с nweb
Пришло время начать исследование. Запустим еще один xterm и воспользуемся для трассировки запущенного nweb-сервера. Для того чтобы сделать это, нужно знать идентификатор процесса программы и иметь соответствующие права доступа. Будем рассматривать только определенные системные вызовы — те, которые имеют отношение к сети. Для начала необходимо ввести команду, показанную в первой строке , используя идентификатор процесса nweb, выведенный ранее. Должен быть показан следующий вывод — строка 2 .
Листинг 4. Запуск трассировки nweb’а
$ strace -e trace=network -p 4009 accept(0,
Отметим, что трассировка останавливается в середине вызова сетевой функции . Необходимо несколько раз обновить страницу в Web-браузере, чтобы увидеть, что отображает каждое обновление страницы. Не великолепно ли? Мы видим низкоуровневые сетевые вызовы HTTP-сервера , которые были вызваны Web-браузером. Буквально говоря, принимает запросы Web-браузера.
Можно остановить трассировку сетевых вызовов запущенного процесса nweb, нажав Ctrl+C, когда текущим является окно xterm c запущенным strace.
Примеры трассировки сети в Linux
Например, выполним трассировку до сервера losst.ru:

Как видите, пакет прошел через 6 узлов перед тем, как дойти до цели. На каждый узел отправлялось по три пакета и для каждого из них было засечено время прохождения. И если на одном из узлов возникнет проблема, теперь вы будете знать на каком.
У вас, наверное, возник вопрос, почему время прохождения для некоторых узлов такое долгое? Ведь если выполнить ping, то общее время будет намного меньше. Дело в том, что время засекается для пути пакета туда и обратно. От запроса до ответа. Это раз, но еще нужно учитывать что маршрутизаторы дают высший приоритет для приходящих пакетов, когда для сервисных задержки могут быть более длинными.

Еще, вместо одного узла вы можете видеть звездочки traceroute. Это еще не значит, что он не работает. Это означает что всего лишь он не захотел нам отвечать. Давайте проверим еще что-нибудь, например, публичный DNS google:

Здесь уже больше узлов, и такая же ситуация со звездочками. Если бы на пути к серверу возникла ошибка, мы бы это увидели. Например, узел 195.153.14.1 нам не ответил и мы смогли отследить запрос только до 212.162.26.169.

Иногда трассировка с помощью UDP не работает, это может произойти потому, что фаервол блокирует все лишние пакеты. Мы можем воспользоваться ICMP с помощью опции -I.


Но трассировка может использоваться не только для обнаружения обрыва в цепочке маршрутизаторов. У нее еще есть достаточно интересное применение по исследованию сети. Например, вы можете попытаться определить использование подсетей провайдером. Отправим три запроса на разные адреса:

Затем сравните выводы этих команд. Вы увидите, что начальные IP адреса одинаковые. Мы можем сделать вывод, что наш роутер 192.168.1.1 подключен к локальной сети провайдера 195.5.8.0/24, которая, в свою очередь, подключена к сети 10.50.50.0/24 откуда уже получает доступ к внешней сети.
EXPRESSIONS top
Ltrace has support for some elementary expressions. Each expression
can be either of the following:
NUM An integer number.
argNUM Value of NUM-th argument. The expression has the same value
as the corresponding argument. arg1 refers to the first
argument, arg0 to the return value of the given function.
retval Return value of function, same as arg0.
eltNUM Value of NUM-th element of the surrounding structure type.
E.g. struct(ulong,array(int,elt1)) describes a structure
whose first element is a length, and second element an array
of ints of that length.
zero
zero(EXPR)
Describes array which extends until the first element, whose
each byte is 0. If an expression is given, that is the
maximum length of the array. If NUL terminator is not found
earlier, that's where the array ends.
Examples
traceroute computerhope.com
Trace the route that packets take between your system and the host named computerhope.com, using the default method (udp datagram, 16 simultaneous probes). The results will look similar to the following output:
traceroute to computerhope.com (166.70.10.23), 30 hops max, 60 byte packets 1 176.221.87.1 (176.221.87.1) 1.474 ms 1.444 ms 1.390 ms 2 f126.broadband2.quicknet.se (92.43.37.126) 10.047 ms 19.868 ms 23.156 ms 3 10.5.12.1 (10.5.12.1) 24.098 ms 24.340 ms 25.311 ms 4 212.247.178.9 (212.247.178.9) 25.777 ms 27.184 ms 27.625 ms 5 vst-ncore-1.bundle-ether1.tele2.net (130.244.39.46) 30.632 ms 31.610 ms 32.194 ms 6 kst5-core-1.bundle-ether6.tele2.net (130.244.71.178) 33.608 ms 15.274 ms 16.449 ms 7 kst5-peer-1.ae0-unit0.tele2.net (130.244.205.125) 252.53 ms 11.169 ms 12.158 ms 8 avk6-peer-1.ae0-unit0.tele2.net (130.244.64.71) 19.661 ms 25.765 ms 26.730 ms 9 peer-as3257.avk6.tele2.net (130.244.200.106) 25.390 ms 24.863 ms xe-5-0-0.nyc30.ip4.tinet.net (89.149.181.109) 23.626 ms 10 fortress-gw.ip4.tinet.net (216.221.158.90) 29.943 ms 31.112 ms 29.002 ms 11 208.116.63.254 (208.116.63.254) 32.102 ms 29.862 ms 29.337 ms
Notes
To speed up work, normally several probes are sent simultaneously. The downside is that this creates a «storm of packages», especially in the reply direction. Routers can throttle the rate of icmp responses, and some of replies can be lost. To avoid this, decrease the number of simultaneous probes, or even set it to 1 (like in initial traceroute implementation), i.e. -N 1
The final (target) host can drop some of the simultaneous probes, and might even answer only the latest ones. It can lead to extra «looks like expired» hops near the final hop. traceroute uses a smart algorithm to auto-detect such a situation, but if it cannot help in your case, just use -N 1.
For even greater stability you can slow down the program’s work with the -z option. For example, use -z 0.5 for a half-second pause between probes.
If some hops report nothing for every method, the last chance to obtain something is to use the ping command with the -R option (IPv4, and for nearest 8 hops only).
Strace from the standpoint of a system administrator
Using strace requires some basic hacking instinct. It’s not for everyone. Most desktop users will probably
never need or want to use strace, but they just might. Likewise, most system administrators doing level I
maintenance or helpdesk will probably not be tempted to put strace to good use.
However, if you have a curious nature or would like to understand better what your system is doing or perhaps
your job requires that you dabble into the internals, then strace is a good place to start and then spend some
time, never quite leaving. Like Hotel California, that is.
Now, when and how to use strace — and most importantly — what kind of information to pay attention to, this
kind of takes a form of black art, but with some discipline and an inkling to code, you will be able to master
strace and use it successfully.
Basic usage
First, to learn the basics, please read the man page.
strace can be invoked against a command line, which can be a binary or a script, or attached against an already
running process. Output can be shown on the screen, but this is usually of limited value unless the runs are
really short and simple, or redirected into a file, which is the preferred way of doing things.
Special flags can be used to measure system call timing, inside the system calls and in between them, child
processes forked off the parent can also be traced, environment variables can also be shown, there’s the string
length for the output, the ability to filter only specific system calls, and create a useful summary for the
entire run.
Here’s the most basic form:
strace <command-line>
Here’s an example, with dd command:
strace dd if=/dev/zero of=/tmp/file bs=1024K count=5

This will produce the following output:

Looks cluttered and messy and not easy to follow. Indeed, this is not how you should be using strace unless you
can read really, really fast, kind of Dustin Hoffman in Rain Man.
COLOPHON top
This page is part of the LTTng-UST ( LTTng Userspace Tracer)
project. Information about the project can be found at
⟨http://lttng.org/⟩. It is not known how to report bugs for this man
page; if you know, please send a mail to man-pages@man7.org. This
page was obtained from the tarball lttng-ust-2.11.0.tar.bz2 fetched
from ⟨https://lttng.org/files/lttng-ust/⟩ on 2019-11-19. If you dis‐
cover any rendering problems in this HTML version of the page, or you
believe there is a better or more up-to-date source for the page, or
you have corrections or improvements to the information in this
COLOPHON (which is not part of the original manual page), send a mail
to man-pages@man7.org
LTTng 2.10.6 10/17/2019 TRACELOG(3)
Pages that refer to this page:
do_tracepoint(3),
lttng-ust(3),
tracef(3),
tracepoint(3),
tracepoint_enabled(3)







