AWS CodeBuild使用nohup运行后台任务出现wait命令报错如何解决
报错原因
AWS CodeBuild 的 buildspec 配置中,commands 下的每一行独立条目都会在单独的子 shell 中执行:
- 第一行
nohup sleep 30 & echo $! > pidfile执行时,启动的后台进程是当前子 shell 的子进程 - 第二行
wait $(cat pidfile)在新的子 shell 中执行,该 shell 没有对应 PID 的子进程,因此抛出「pid 不是当前 shell 的子进程」的报错
解决方案
你可以将关联的命令合并到同一行执行,保证它们在同一个子 shell 中运行,修改后的 buildspec 如下:
version: 0.2 phases: build: commands: - nohup sleep 30 & echo $! > pidfile && wait $(cat pidfile)
如果你的操作逻辑更复杂,也可以将所有关联逻辑写入单独的 shell 脚本后执行,示例如下:
- 首先在代码库中新增
run_background_task.sh文件,内容为:
#!/bin/bash nohup sleep 30 & echo $! > pidfile wait $(cat pidfile)
- 修改 buildspec 执行该脚本:
version: 0.2 phases: build: commands: - chmod +x run_background_task.sh - ./run_background_task.sh
如果不需要持久化存储 PID,也可以直接将 PID 存入变量直接等待,简化写法:
version: 0.2 phases: build: commands: - nohup sleep 30 & BG_PID=$! && wait $BG_PID
内容的提问来源于stack exchange,提问作者Bhargav Mg
相关产品推荐
相关产品推荐

