ngx_os_specific_init
声明在 src/os/unix/ngx_os.h
ngx_int_t ngx_os_specific_init(ngx_log_t *log);
定义在 src\os\unix\ngx_linux_init.c
ngx_int_t ngx_os_specific_init(ngx_log_t *log) { struct utsname u; if (uname(&u) == -1) { ngx_log_error(NGX_LOG_ALERT, log, ngx_errno, "uname() failed"); return NGX_ERROR; } (void) ngx_cpystrn(ngx_linux_kern_ostype, (u_char *) u.sysname, sizeof(ngx_linux_kern_ostype)); (void) ngx_cpystrn(ngx_linux_kern_osrelease, (u_char *) u.release, sizeof(ngx_linux_kern_osrelease)); ngx_os_io = ngx_linux_io; return NGX_OK; }
通过调用系统调用
uname
获取操作系统的类型和版本信息,并将其存储到全局变量中,同时设置与操作系统相关的 I/O 方法
主要逻辑
开始 │ ├─→ 调用uname(&u) │ │ │ ├─失败→ 记录ALERT日志 → 返回NGX_ERROR │ │ │ └─成功→ 复制sysname到ngx_linux_kern_ostype │ │ │ → 复制release到ngx_linux_kern_osrelease │ │ │ → 设置ngx_os_io = ngx_linux_io │ │ │ → 返回NGX_OK │ 结束
详解
调用
uname
获取系统信息struct utsname u; if (uname(&u) == -1) { ngx_log_error(NGX_LOG_ALERT, log, ngx_errno, "uname() failed"); return NGX_ERROR; }
uname
系统调用 :uname
是一个 POSIX 标准的系统调用,用于获取当前操作系统的基本信息(如系统名称、内核版本等)。它将结果填充到struct utsname
结构体中。- 错误处理 :如果
uname
调用失败(返回值为-1
),会记录错误日志并返回NGX_ERROR
,表示初始化失败。
uname
在 C 语言中,
uname
函数用于获取当前操作系统的相关信息。它是 POSIX 标准的一部分,定义在<sys/utsname.h>
头文件中。通过调用uname
函数,可以获取系统名称、节点名称(主机名)、操作系统版本、机器硬件架构等信息。函数原型
#include <sys/utsname.h> int uname(struct utsname *buf);
参数说明
buf
是一个指向struct utsname
的指针,函数会将系统信息填充到这个结构体中。返回值
- 成功时返回
0
。- 失败时返回
-1
,并设置errno
来指示错误原因。
struct utsname
定义如下:struct utsname { char sysname[]; // 操作系统名称(例如 "Linux") char nodename[]; // 节点名称(通常是主机名) char release[]; // 操作系统发行版本 char version[]; // 操作系统版本信息 char machine[]; // 硬件架构(例如 "x86_64") };
每个字段是一个字符数组,存储了对应的信息
复制系统类型和版本信息
(void) ngx_cpystrn(ngx_linux_kern_ostype, (u_char *) u.sysname, sizeof(ngx_linux_kern_ostype)); (void) ngx_cpystrn(ngx_linux_kern_osrelease, (u_char *) u.release, sizeof(ngx_linux_kern_osrelease));
u.sysname
和u.release
:
u.sysname
:表示操作系统的名称(如"Linux"
)。u.release
:表示内核的版本号(如"5.4.0-42-generic"
)。- 全局变量 :
ngx_linux_kern_ostype
:存储操作系统名称。ngx_linux_kern_osrelease
:存储内核版本号。
设置操作系统相关的 I/O 方法
ngx_os_io = ngx_linux_io;
ngx_os_io
:是一个全局变量,指向与操作系统相关的 I/O 方法集合(如文件读写、网络通信等)。ngx_linux_io
:是针对 Linux 系统实现的一组 I/O 方法。
ngx_os_io
定义在 src\os\unix\ngx_posix_init.c
ngx_os_io_t ngx_os_io = { ngx_unix_recv, ngx_readv_chain, ngx_udp_unix_recv, ngx_unix_send, ngx_udp_unix_send, ngx_udp_unix_sendmsg_chain, ngx_writev_chain, 0 };
ngx_linux_io
定义在 src\os\unix\ngx_linux_init.c
static ngx_os_io_t ngx_linux_io = { ngx_unix_recv, ngx_readv_chain, ngx_udp_unix_recv, ngx_unix_send, ngx_udp_unix_send, ngx_udp_unix_sendmsg_chain, #if (NGX_HAVE_SENDFILE) ngx_linux_sendfile_chain, NGX_IO_SENDFILE #else ngx_writev_chain, 0 #endif };
ngx_os_io_t
Ubuntu 下 nginx-1.24.0 源码分析 - ngx_os_io_t 类型-CSDN博客
返回成功状态
return NGX_OK;
- 如果所有步骤都成功执行,则返回
NGX_OK
,表示初始化完成。