shell: Lua模块用于非阻塞系统shell命令执行
安装
如果您尚未设置RPM仓库订阅,请注册。然后您可以继续以下步骤。
CentOS/RHEL 7或Amazon Linux 2
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install lua-resty-shell
CentOS/RHEL 8+、Fedora Linux、Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install lua5.1-resty-shell
要在NGINX中使用此Lua库,请确保已安装nginx-module-lua。
本文档描述了lua-resty-shell v0.3,于2020年7月1日发布。
local shell = require "resty.shell"
local stdin = "hello"
local timeout = 1000 -- ms
local max_size = 4096 -- byte
local ok, stdout, stderr, reason, status =
shell.run([[perl -e 'warn "he\n"; print <>']], stdin, timeout, max_size)
if not ok then
-- ...
end
函数
run
语法: ok, stdout, stderr, reason, status = shell.run(cmd, stdin?, timeout?, max_size?)
上下文: 所有支持yield的阶段
运行一个shell命令cmd,可选的stdin。
cmd参数可以是一个单独的字符串值(例如"echo 'hello, world'")或一个类数组的Lua表(例如{"echo", "hello, world"})。前者等价于{"/bin/sh", "-c", "echo 'hello, world'"},但更简单且稍微快一些。
当stdin参数为nil或""时,stdin设备将立即关闭。
timeout参数指定了超时阈值(以毫秒为单位),用于stderr/stdout读取超时、stdin写入超时和进程等待超时。
max_size参数指定了stdout和stderr每个输出数据流允许的最大大小。当超过限制时,run()函数将立即停止从流中读取更多数据,并在reason返回值中返回错误字符串:"failed to read stdout: too much data"。
成功终止时(以零退出状态),ok将为true,reason将为"exit",status将包含子进程的退出状态。
异常终止时(非零退出状态),ok将为false,reason将为"exit",status将包含子进程的退出状态。
当超过超时阈值或发生其他意外错误时,ok将为nil,reason将是描述错误的字符串。
当超时阈值被超过时,子进程将被如下方式终止:
- 首先,接收来自此库的
SIGTERM信号, - 然后,在1毫秒后,接收来自此库的
SIGKILL信号。
请注意,子进程的子进程(如果有)将不会被终止。您可能需要自行终止这些进程。
当子进程被UNIX信号终止时,reason返回值将为"signal",status返回值将包含信号编号。
GitHub
您可以在nginx-module-shell的GitHub仓库中找到此模块的其他配置提示和文档。