Reputation: 31
I have many process running on my system. Thare is one common API which is being called by each process. So I want to check at run time that from which process this particular API is called and according I want to put some checks. Code is in c/unix
Upvotes: 0
Views: 259
Reputation: 1927
Ok, what do you mean by API? Is it a library? Is it a system call? You need strace or ltrace command. Strace is for system calls, ltrace is for general library calls.
Say I want to trace what files does this program open:
#include <stdio.h>
void main() {
printf(Hello World");
}
I would check this by:
$ strace ./a.out
execve("./a.out", ["./a.out"], [/* 68 vars */]) = 0
brk(0) = 0x2115000
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fea9ff0d000
access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=146271, ...}) = 0
mmap(NULL, 146271, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fea9fee9000
close(3) = 0
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\320\37\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1840928, ...}) = 0
mmap(NULL, 3949248, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fea9f928000
mprotect(0x7fea9fae3000, 2093056, PROT_NONE) = 0
mmap(0x7fea9fce2000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ba000) = 0x7fea9fce2000
mmap(0x7fea9fce8000, 17088, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fea9fce8000
close(3) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fea9fee8000
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fea9fee6000
arch_prctl(ARCH_SET_FS, 0x7fea9fee6740) = 0
mprotect(0x7fea9fce2000, 16384, PROT_READ) = 0
mprotect(0x600000, 4096, PROT_READ) = 0
mprotect(0x7fea9ff0f000, 4096, PROT_READ) = 0
munmap(0x7fea9fee9000, 146271) = 0
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 6), ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fea9ff0c000
write(1, "Hello World", 11Hello World) = 11
exit_group(11) = ?
+++ exited with 11 +++
So we see that this process calls the open function two times. You can trace the arguments too.
You can also attach strace / ltrace to an already running process:
strace -p <PID>
Then all you have to do is search / monitor for the desired function call, and act accordingly
Upvotes: 2