跳到内容

第六章 C/POSIX 互操作与底层特性 ​

6.1 函数指针 ​

源码出处:dumpsys.cpp:85-98

cpp
static int sort_func(const String16* lhs, const String16* rhs) {
    return lhs->compare(*rhs);
}
// 调用处:
services.sort(sort_func);   // 把函数名(退化为函数指针)传入

语法说明:函数指针是指向函数的指针,可把“某个函数”作为参数传给另一个函数(回调机制)。函数名 sort_func 在传参时自动“退化”为指向该函数的指针。sort 内部通过这个指针调用比较逻辑,约定返回 <0 / 0 / >0 表示大小关系(同 C 的 qsort 比较)。

最小 demo:

cpp
#include <iostream>
#include <algorithm>
// 比较函数指针:返回 <0/0/>0
int cmp_asc(const int* a, const int* b)  { return *a - *b; }
int cmp_desc(const int* a, const int* b) { return *b - *a; }
void sort_with(int* begin, int n, int (*cmp)(const int*, const int*)) {
    // 简易冒泡,用传入的 cmp 比较相邻元素
    for (int i = 0; i < n; ++i)
        for (int j = 0; j + 1 < n - i; ++j)
            if (cmp(&begin[j], &begin[j+1]) > 0) std::swap(begin[j], begin[j+1]);
}
int main() {
    int a[] = {3, 1, 4, 1, 5};
    sort_with(a, 5, cmp_asc);          // 传函数指针(函数名自动退化)
    for (int x : a) std::cout << x << " ";
    std::cout << "\n";
    sort_with(a, 5, cmp_desc);
    for (int x : a) std::cout << x << " ";
    std::cout << "\n";
}

运行结果:

1 1 3 4 5 
5 4 3 1 1

要点:C++ 里通常更推荐用 lambda 或 std::function 替代裸函数指针(更灵活、能捕获状态),但与 C 接口(如 android::Vector::sort)互操作时仍是函数指针最直接。


6.2 C 字符串函数(strcmp / strtol / fprintf / strerror) ​

源码出处:dumpsys.cpp:267, 307, 109, 695

cpp
if (!strcmp(longOptions[optionIndex].name, "skip")) { ... }   // 字符串相等返回 0
timeoutArgMs = strtol(optarg, &endptr, 10);                    // 字符串转 long,base=10
fprintf(stderr, "usage: dumpsys\n" ...);                       // 格式化输出到 stderr
strerror(errno)                                                // errno 转可读字符串

语法说明(均来自 C 标准库 <string.h>/<stdlib.h>/<stdio.h>):

  • strcmp(a, b):逐字节比较两个 C 字符串,相等返回 0。if (!strcmp(a,b)) 即“若相等”。
  • strtol(str, &endptr, base):把字符串按 base 进制解析为 long;endptr 指向首个未解析字符,据此判断是否含非法尾部(如 "10x" 的 x)。
  • fprintf(stream, fmt, ...):按格式串写到指定流(stderr/stdout/文件)。%s 字符串、%d 整数等。
  • strerror(errno):把错误码转成人类可读字符串(如 "Bad file descriptor")。

最小 demo:

cpp
#include <iostream>
#include <cstring>    // strcmp
#include <cstdlib>    // strtol
#include <cstdio>     // fprintf
#include <cerrno>     // errno
#include <unistd.h>   // close
int main() {
    // strcmp
    if (!strcmp("skip", "skip")) std::cout << "equal\n";
    // strtol 带校验
    char* endptr = nullptr;
    long v = strtol("10x", &endptr, 10);
    std::cout << "v=" << v << " tail='" << endptr << "' bad=" << (*endptr != '\0') << "\n";
    // strerror
    close(-1);                       // 必失败,置 errno
    std::cout << "errno=" << errno << ": " << strerror(errno) << "\n";
    // fprintf 到 stderr
    std::fprintf(stderr, "this goes to stderr\n");
}

运行结果:

equal
v=10 tail='x' bad=1
errno=9: Bad file descriptor
this goes to stderr

要点:dumpsys 与大量 C/POSIX 接口打交道,所以混用了 C 字符串函数;它们处理的是 char*(C 风格字符串),而 std::string 用 .c_str() 可转成 char* 交给它们。


6.3 getopt_long 与 struct option ​

源码出处:dumpsys.cpp:237-257, 263-339

cpp
static struct option longOptions[] = {
    {"help", no_argument, 0, 0},
    {"priority", required_argument, 0, 0},
    {"skip", no_argument, 0, 0},
    {0, 0, 0, 0},                       // 结束哨兵
};
c = getopt_long(argc, argv, "+t:T:l", longOptions, &optionIndex);
switch (c) {
    case 0:   /* 命中长选项,用 longOptions[optionIndex].name 区分 */
        if (!strcmp(longOptions[optionIndex].name, "skip")) skipServices = true;
        ...
    case 't': /* -t 的参数在 optarg */ timeoutArgMs = strtol(optarg, &endptr, 10);
    case 'l': showListOnly = true;
    ...
}

语法说明(<getopt.h>,POSIX):

  • struct option { const char* name; int has_arg; int* flag; int val; }:描述一个长选项。has_arg 取 no_argument/required_argument/optional_argument。
  • getopt_long(argc, argv, "短选项串", longOptions, &index):逐次解析命令行,返回命中选项。短选项串中 "t:" 表示 -t 带参数、"l" 表示 -l 不带参数;前缀 "+" 表示遇到非选项参数即停止(POSIXLY_CORRECT 语义)。长选项命中时返回 0 并把索引写入 index;短选项命中返回该字符;解析完毕返回 -1;参数可通过全局指针 optarg 取得,下一个待解析位置由 optind 指示。
  • 命令行约定:选项以 -/-- 开头,其余是位置参数(如 dumpsys activity 中的 activity)。

最小 demo(编译加 -lpthread 不需要,标准库即可;演示 --priority HIGH foo):

cpp
#include <iostream>
#include <getopt.h>
#include <cstring>
int main(int argc, char* const argv[]) {
    static struct option longOpts[] = {
        {"priority", required_argument, 0, 0},
        {"proto",    no_argument,       0, 0},
        {0, 0, 0, 0}
    };
    optind = 1;                              // 重置(便于反复调用,如测试场景)
    while (true) {
        int idx = 0;
        int c = getopt_long(argc, argv, "l", longOpts, &idx);
        if (c == -1) break;                  // 解析完毕
        if (c == 0) {
            if (!strcmp(longOpts[idx].name, "priority"))
                std::cout << "priority=" << optarg << "\n";
            else if (!strcmp(longOpts[idx].name, "proto"))
                std::cout << "proto=true\n";
        } else if (c == 'l') {
            std::cout << "list-only=true\n";
        }
    }
    // optind 之后是位置参数
    for (int i = optind; i < argc; ++i)
        std::cout << "positional[" << i << "]=" << argv[i] << "\n";
    return 0;
}

运行:./demo --priority HIGH foo bar运行结果:

priority=HIGH
positional[3]=foo
positional[4]=bar

要点:optind = 1 必须重置——真实进程里 getopt 首次调用默认 optind=1,但单元测试会在同一进程里反复调 Dumpsys::main(),不重置会从上次位置继续解析导致失败。这正是 dumpsys 在 247 行重置 optind 的原因。


6.4 POSIX 文件/IO(pipe / poll / read / write / signal / getpid) ​

源码出处:main.cpp:73,dumpsys.cpp:693, 826-858

cpp
signal(SIGPIPE, SIG_IGN);                  // 忽略 SIGPIPE,避免写已关闭管道时崩溃
pipe(sfd);                                 // 创建管道:sfd[0]读端, sfd[1]写端
struct pollfd pfd = {.fd = serviceDumpFd, .events = POLLIN};
TEMP_FAILURE_RETRY(poll(&pfd, 1, timeout_ms));   // 带超时等 fd 就绪
TEMP_FAILURE_RETRY(read(redirectFd_.get(), buf, sizeof(buf)));  // 读
WriteFully(fd, buf, rc);                   // 写(循环处理短写)
pid_t myPid = getpid();                    // 取本进程 PID

语法说明(POSIX):

  • signal(sig, handler):为信号 sig 设置处置,SIG_IGN 表示忽略。写已关闭的管道默认触发 SIGPIPE 杀死进程,dumpsys 忽略它改为 write 返回 -1/errno=EPIPE。dumpsys 在 main 里起任何线程前还调了 fflush(stdout)——C 标准 IO 的 stdout 是进程级带缓冲的,若缓冲区里有未写出内容时就创建新线程,这些缓冲会被新线程“看到”,可能导致重复或交错输出;先 fflush 冲干净再起线程,避免这个隐患。
  • pipe(int fildes[2]):创建一对单向管道 fd,fildes[0] 只读、fildes[1] 只写。数据从写端流入、读端流出,中间是内核缓冲区(Linux 上通常 64KB,不经过磁盘)。关键性质:写端写满前不阻塞 writer;缓冲满时 write 阻塞直到读者取走数据(天然背压:读者慢,写者自动慢下来);所有写端都关闭后 read 返回 0(EOF);读端关闭后写端 write 返回 -1/EPIPE(默认发 SIGPIPE)。
  • poll(pollfd[], n, timeout_ms):多路复用,等待一组 fd 中任一就绪或超时。struct pollfd 两字段:events(你关心的事件,输入,POLLIN=可读/POLLOUT=可写)、revents(内核回填的实际发生事件,输出)。除你关心的外,revents 还可能含 POLLHUP(挂断,pipe 所有写端已关)、POLLERR(出错)、POLLNVAL(fd 不合法)。返回 >0 就绪数、==0 超时、<0 出错。
    • 易踩坑:写端关闭时若管道里还有未读数据,poll 返回 revents = POLLIN | POLLHUP(两者同时)。不能看到 POLLHUP 就以为“结束了”——必须继续 read 把残留数据排干,直到 read 返回 0 才是真 EOF。dumpsys 的读循环就绪就读、读完再 poll,直到 read==0 才停。
  • read(fd, buf, n):从 fd 读最多 n 字节,返回实际读取字节数。返回 >0 时可能小于 n(短读——当前管道里就这么多数据,不是错误,要继续读);==0 表示 EOF(所有写端已关);<0 出错(被信号中断时 errno=EINTR,见 6.5)。
  • write(fd, buf, n):向 fd 写最多 n 字节,返回实际写入字节数。返回 >0 时可能小于 n(短写——尤其 n 较大或缓冲可用空间不足时),要把剩余部分继续写完;读端已关闭时返回 -1/errno=EPIPE。正确写法是循环 write 直到 n 字节全部写出——dumpsys 把这个细节交给 WriteFully(fd, buf, n)(<android-base/file.h>),它内部循环 write 处理短写,单次 write 不保证写满:
    cpp
    // ❌ 错误:只 write 一次,可能只写一部分,输出被截断
    write(fd, buf, rc);
    // ✅ 正确:循环写直到写满(WriteFully 的语义)
    ssize_t off = 0;
    while (off < rc) {
        ssize_t w = write(fd, buf + off, rc - off);
        if (w < 0) { if (errno == EINTR) continue; break; }
        off += w;
    }
  • getpid():返回当前进程 PID。

最小 demo(编译:g++ -std=c++17 demo.cpp -o demo -lpthread):用 pipe + poll 演示“子写父读带超时”的核心机制(dumpsys 用线程而非 fork,但管道搬运原理相同):

cpp
#include <iostream>
#include <unistd.h>     // pipe, read, write, getpid
#include <signal.h>     // signal, SIGPIPE, SIG_IGN
#include <poll.h>       // poll, pollfd, POLLIN
#include <cstring>      // strerror
#include <cerrno>
int main() {
    signal(SIGPIPE, SIG_IGN);          // 忽略 SIGPIPE
    int p[2];
    if (pipe(p) != 0) { std::perror("pipe"); return 1; }
    // 直接在主线程写一点数据到写端 p[1],再从读端 p[0] poll+read
    const char* msg = "hello from pipe";
    write(p[1], msg, std::strlen(msg));
    close(p[1]);                       // 关写端,读端读完后会 EOF

    struct pollfd pfd = {.fd = p[0], .events = POLLIN};
    int rc = poll(&pfd, 1, 1000);      // 等 1 秒
    if (rc > 0 && (pfd.revents & POLLIN)) {
        char buf[64];
        ssize_t n = read(p[0], buf, sizeof(buf) - 1);
        if (n > 0) { buf[n] = '\0'; std::cout << "read: " << buf << "\n"; }
    }
    close(p[0]);
    std::cout << "my pid=" << getpid() << "\n";
}

运行结果:

read: hello from pipe
my pid=12345

最小 demo 2(pollfd 事件位 + 残留数据排干,编译加 -lpthread):演示“写端关闭时管道里仍有数据 → POLLIN|POLLHUP 同时返回,必须排干才能看到真 EOF”:

cpp
#include <iostream>
#include <unistd.h>
#include <poll.h>
int main() {
    int p[2]; pipe(p);
    write(p[1], "abc", 3);      // 先写 3 字节
    close(p[1]);                // 关写端(数据仍在管道里)
    struct pollfd pfd{.fd = p[0], .events = POLLIN};
    while (true) {
        int rc = poll(&pfd, 1, 1000);
        if (rc <= 0) break;
        std::cout << "revents=" << pfd.revents
                  << (pfd.revents & POLLIN  ? " POLLIN"  : "")
                  << (pfd.revents & POLLHUP ? " POLLHUP" : "") << "\n";
        char buf[8];
        ssize_t n = read(p[0], buf, sizeof(buf));
        if (n <= 0) { std::cout << "read=" << n << " -> EOF\n"; break; }
        std::cout << "  read " << n << ": " << std::string(buf, n) << "\n";
    }
    close(p[0]);
}

运行结果(Linux 上 POLLIN=1、POLLHUP=16,故 17=POLLIN|POLLHUP):

revents=17 POLLIN POLLHUP
  read 3: abc
revents=16 POLLHUP
read=0 -> EOF

第一次:有数据 + 写端已关 → POLLIN|POLLHUP,读出 abc;第二次:数据排干、写端已关 → 仅 POLLHUP,read 返回 0 → 真 EOF。

要点:dumpsys 的核心设计就是“工作线程把 dump 内容写到 pipe 写端,主线程用 poll(timeout) 从读端读”,从而把可能永久阻塞的 service->dump() 与带超时的读取解耦——这正是上面的 pipe+poll 机制。


6.5 TEMP_FAILURE_RETRY 宏 ​

源码出处:dumpsys.cpp:842, 858

cpp
int rc = TEMP_FAILURE_RETRY(poll(&pfd, 1, time_left_ms()));
rc = TEMP_FAILURE_RETRY(read(redirectFd_.get(), buf, sizeof(buf)));

语法说明:TEMP_FAILURE_RETRY(expr) 是 glibc/Bionic 提供的宏,把被 EINTR(被信号中断)的系统调用自动重试。慢系统调用(poll/read/write)在进程收到信号时可能被中断返回 -1 且 errno=EINTR,若不处理会被误判为出错;该宏等价于:

cpp
// 简化语义
typeof(expr) _r;
do { _r = (expr); } while (_r < 0 && errno == EINTR);

最小 demo(用宏模拟,演示被中断后重试的思路):

cpp
#include <iostream>
#include <cerrno>
// 模拟一个会被信号中断的系统调用:前两次返回 -1 且 errno=EINTR,第三次成功
int fake_syscall(int& call) {
    if (++call < 3) { errno = EINTR; return -1; }
    return 42;
}
#define TEMP_FAILURE_RETRY(expr) ({          \
    decltype(expr) _r; int _e;               \
    do { _r = (expr); _e = errno; }          \
    while (_r == -1 && _e == EINTR);         \
    _r; })
int main() {
    int call = 0;
    int rc = TEMP_FAILURE_RETRY(fake_syscall(call));
    std::cout << "rc=" << rc << " calls=" << call << "\n";   // 重试到成功
}

运行结果:

rc=42 calls=3

要点:poll/read 在 dumpsys 运行期间可能被各种信号打断,用 TEMP_FAILURE_RETRY 包裹保证“只是被打断”时不会误退出循环。


6.6 指定初始化(designated initializers) ​

源码出处:dumpsys.cpp:826

cpp
struct pollfd pfd = {.fd = serviceDumpFd, .events = POLLIN};

语法说明:指定初始化允许按成员名(而非位置)初始化结构体,形如 {.成员 = 值, .成员 = 值}。它源自 C99,C++20 起正式纳入标准(此前作为 GNU 扩展被广泛支持)。未显式初始化的成员自动置零。优点:可读性好、不怕结构体字段顺序调整。

最小 demo:

cpp
#include <iostream>
#include <poll.h>     // pollfd
int main() {
    // 用 .field = value 按名字初始化,未写的 revents 自动为 0
    struct pollfd pfd = {.fd = 5, .events = POLLIN};
    std::cout << "fd=" << pfd.fd << " events=" << pfd.events << " revents=" << pfd.revents << "\n";
    // 普通 struct 同样适用
    struct Point { int x, y, z; };
    Point pt = {.x = 1, .z = 3};      // y 未写 -> 0
    std::cout << "pt=" << pt.x << "," << pt.y << "," << pt.z << "\n";
}

运行结果:

fd=5 events=1 revents=0
pt=1,0,3

要点:相比 struct pollfd pfd = {serviceDumpFd, POLLIN}(依赖位置、易错),指定初始化更清晰。


6.7 位运算符 & / | ​

源码出处:dumpsys.cpp:288-296, 710-732

cpp
dumpTypeFlags |= TYPE_DUMP;            // 设置位:flags = flags | TYPE_DUMP
if (dumpTypeFlags & TYPE_PID) { ... }  // 测试位:flags & TYPE_PID != 0 则包含该类型

语法说明:

  • |(按位或):对应位任一为 1 则结果该位为 1。a |= b 把 b 的那些位“合并”进 a(设置标志)。
  • &(按位与):对应位都为 1 结果才为 1。a & b 非 0 表示 a 中含有 b 的某些位(测试标志)。
  • 配合 2 的幂的枚举值,可在一个整数里存多个布尔开关。

最小 demo:

cpp
#include <iostream>
enum Flag { A = 0x1, B = 0x2, C = 0x4 };
int main() {
    int f = 0;
    f |= A;                 // 设置 A -> 0b001
    f |= C;                 // 设置 C -> 0b101
    std::cout << "f=" << f << "\n";
    if (f & A) std::cout << "has A\n";
    if (f & B) std::cout << "has B\n";    // 不打印
    if (f & C) std::cout << "has C\n";
    f &= ~A;                // 清除 A(~A 取反)
    std::cout << "after clear A, f& A=" << (f & A) << "\n";
}

运行结果:

f=5
has A
has C
after clear A, f& A=0

要点:dumpsys 用 dumpTypeFlags |= TYPE_PID 累加用户指定的 dump 类型,再用 dumpTypeFlags & TYPE_PID 在工作线程里逐项判断要不要执行对应输出——一套位运算实现“多类型组合 dump”。