linux中strace记录所有的系统调用

发布时间:2019-12-09编辑:脚本学堂
命令格式: #strace -o log.txt ./t 其中 log.txt 是strace命令创建的文件用以保存应用程序中所有的系统调用的信息

命令格式:
#strace -o log.txt ./t

其中 log.txt 是strace命令创建的文件用以保存应用程序中所有的系统调用的信息
     t 文件时通过 gcc 编译出的可执行的文件 如:gcc test.c -o t

test.c
 

复制代码 代码如下:

    #include <stdio.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <malloc.h>

    int main(void)
    {
        int        handle,bytes;
        void    *ptr;

        handle    = open("hello.txt",O_RDONLY);
       
        ptr        = (void*)malloc(150);
       
        bytes    = read(handle,ptr,150);
        printf("%sn",(char*)ptr);

        free(ptr);
        close(handle);
        return 0;
    }

log.sh
 

复制代码 代码如下:
#!/bin/bash
echo "hello" > hello.txt
gcc test.c    -o t
strace -o log.txt ./t
exit

则通过 strace 生成的 log.txt 文件内容如下:
   

复制代码 代码如下:
execve("./t", ["./t"], [/* 44 vars */]) = 0
    brk(0) = 0x925a000
    access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
    mmap2(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb783f000
    access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)
    open("/etc/ld.so.cache", O_RDONLY) = 3
    fstat64(3, {st_mode=S_IFREG|0644, st_size=64033, ...}) = 0
    mmap2(NULL, 64033, PROT_READ, MAP_PRIVATE, 3, 0) = 0xb782f000
    close(3) = 0
    access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
    open("/lib/i386-linux-gnu/libc.so.6", O_RDONLY) = 3
    read(3, "177ELF111331p2221004"..., 512) = 512
    fstat64(3, {st_mode=S_IFREG|0755, st_size=1544392, ...}) = 0
    mmap2(NULL, 1554968, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x8fd000
    mmap2(0xa73000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x176) = 0xa73000
    mmap2(0xa76000, 10776, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xa76000
    close(3) = 0
    mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb782e000
    set_thread_area({entry_number:-1 -> 6, base_addr:0xb782e8d0, limit:1048575, seg_32bit:1, contents:0, read_exec_only:0, limit_in_pages:1, seg_not_present:0, useable:1}) = 0
    mprotect(0xa73000, 8192, PROT_READ) = 0
    mprotect(0x8049000, 4096, PROT_READ) = 0
    mprotect(0x22e000, 4096, PROT_READ) = 0
    munmap(0xb782f000, 64033) = 0
    open("hello.txt", O_RDONLY) = 3
    brk(0) = 0x925a000
    brk(0x927b000) = 0x927b000
    read(3, "hellon", 150) = 6
    fstat64(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0
    mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb783e000
    write(1, "hellon", 6) = 6
    write(1, "n", 1) = 1
    close(3) = 0
    exit_group(0) = ?
 

使用 strace 的令一个好处就是不需要跟踪应用程序的源代码就可以了解其内部结构和运作方式。