Mac上用Visual Studio Code调试Nginx

前言

学习nginx最好的方式是阅读源代码跟调试,本文介绍的是在Visual Studio Code调试Nginx,首先感谢Microsoft推出免费好用的VS code,真的很赞;

编译Nginx

  • 详细编译:https://www.jianshu.com/p/82ba1b335abf
  • 修改编参数
    1. 修改 /auto/cc/conf 文件,将ngx_compile_opt="-c" 修改为 ngx_compile_opt="-c -g";
    2. 关掉Nginx的后台进程运行方式,在/conf/nginx.conf 中添加一行:
daemon off;

为什么要加-g参数?
-g 在编译的时候,产生调试信息

为什么要关闭后台进程?
nginx在启动后,在unix系统中会以daemon的方式在后台运行,后台进程包含一个master进程和多个worker进程。
我们也可以手动地关掉后台模式,让nginx在前台运行,并且通过配置让nginx取消master进程,从而可以使nginx以单进程方式运行。
很显然,生产环境下我们肯定不会这么做,所以关闭后台模式,一般是用来调试用的。
参考:Nginx开发从入门到精通

调试Master进程

  • 添加VSCODE调试配置,创建并修改launch.json:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "dubug nginx",
            "type": "cppdbg",
            "request": "launch",
            "program":  "${workspaceFolder}/bin/nginx", //nginx运行目录
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "lldb"
        }
    ]
}
  • 调试效果


    nginx_debug.jpg

调试Worker进程

  • 查找Worker进程pid
Last login: Thu Jun 13 11:22:42 on ttys005
xxx:~ xx$ ps -ef | grep nginx
  502 66524     1   0  9:58上午 ??         0:00.00 nginx: master process ./bin/nginx
  502    66524   0  9:58上午 ??         0:00.00 nginx: worker process
  502 68007 68009   0 11:22上午 ??         0:00.01 /Users/ali/Documents/work/nginx-1.17.0/bin/nginx
  502 68362 68132   0 11:29上午 ttys000    0:00.00 grep nginx
  • 编辑 launch.json,添加 Attach配置
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        { 
            "name": "debug nginx worker",
            "type": "cppdbg",
            "request": "attach",
            "program": "${workspaceFolder}/bin/nginx",
            "processId": "69325",
            "MIMode": "lldb"
        },
        {
            "name": "debug nginx master",
            "type": "cppdbg",
            "request": "launch",
            "program":  "${workspaceFolder}/bin/nginx",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "lldb"
        }
    ]
}
  • 调试效果


    nginx_debug_workder.jpg

总结:

1、VS Code调试真是方便,开发C/C++神器;
2、Nginx非常成熟,整个社区也是非常成熟,提供了很多资料解决很多的问题;
3、阅读Nginx代码就是一种生活享受,大家也一起来尽情遨游吧!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容