• 编程调试
    • GDB调试
      • 进入 gdb
      • gdbinit
      • 设置断点
      • 打印当前进程的所有协程和状态
      • 打印当前运行时协程的调用栈
      • 打印指定协程id的调用战
      • 打印全局协程的状态
  • PHP代码调试

    编程调试

    使用Swoole协程时,可以使用下面的方法进行调试

    GDB调试

    进入 gdb

    1. gdb php test.php

    gdbinit

    1. (gdb) source /path/to/swoole-src/gdbinit

    设置断点

    例如 co::sleep 函数

    1. (gdb) b zim_swoole_coroutine_util_sleep

    打印当前进程的所有协程和状态

    1. (gdb) co_list
    2. coroutine 1 SW_CORO_YIELD
    3. coroutine 2 SW_CORO_RUNNING

    打印当前运行时协程的调用栈

    1. (gdb) co_bt
    2. coroutine cid:[2]
    3. [0x7ffff148a100] Swoole\Coroutine->sleep(0.500000) [internal function]
    4. [0x7ffff148a0a0] {closure}() /home/shiguangqi/php/swoole-src/examples/coroutine/exception/test.php:7
    5. [0x7ffff141e0c0] go(object[0x7ffff141e110]) [internal function]
    6. [0x7ffff141e030] (main) /home/shiguangqi/php/swoole-src/examples/coroutine/exception/test.php:10

    打印指定协程id的调用战

    1. (gdb) co_bt 1
    2. [0x7ffff1487100] Swoole\Coroutine->sleep(0.500000) [internal function]
    3. [0x7ffff14870a0] {closure}() /home/shiguangqi/php/swoole-src/examples/coroutine/exception/test.php:3
    4. [0x7ffff141e0c0] go(object[0x7ffff141e110]) [internal function]
    5. [0x7ffff141e030] (main) /home/shiguangqi/php/swoole-src/examples/coroutine/exception/test.php:10

    打印全局协程的状态

    1. (gdb) co_status
    2. stack_size: 2097152
    3. call_stack_size: 1
    4. active: 1
    5. coro_num: 2
    6. max_coro_num: 3000
    7. peak_coro_num: 2

    PHP代码调试

    遍历当前进程内的所有协程,并打印调用栈。

    1. function Coroutine::listCoroutines() : Iterator
    需要4.1.0或更高版本
    • 返回迭代器,可使用foreach遍历,或使用iterator_to_array转为数组
    1. $coros = Coroutine::listCoroutines();
    2. foreach($coros as $cid)
    3. {
    4. var_dump(Coroutine::getBackTrace($cid));
    5. }