龙空技术网

linux shell-脚本中调用fg调取后台任务报错

linux运维菜 395

前言:

目前同学们对“nginx挂掉原因”大体比较注意,看官们都需要剖析一些“nginx挂掉原因”的相关知识。那么小编同时在网摘上汇集了一些关于“nginx挂掉原因””的相关知识,希望同学们能喜欢,各位老铁们一起来学习一下吧!

前言

今天在制作docker镜像的时候,需要让nginx在前台执行,但是在nginx执行之后,需要获取nginx端口,添加加一个针对nginx监控的程序,而且要求如果nginx挂掉,这个容器就必须销毁。

思路

在bash中,后台执行程序可以在命令参数之后加上 & 即可,如果需要继续前台执行 fg jobid。

例如下面写一个enterypoint脚本

#!/bin/bash

/opt/nginx/sbin/nginx -g "daemon off;" &

PORT=$(ss -lntpd | grep '\"nginx\"' | awk '{split($5,a,":");print a[2]}'|head -n 1)

/nginx-monitor &

fg 1 >> /data/startup.log 2>&1

发现容器启动之后就关闭了,说明脚本有问题,没有程序在前台执行导致容器直接退出。

通过日志文件发现有报错:fg: no job control

通过man bash查看帮助

找到JOB CONTROL

A user typically employs this facility via an interactive interface supplied jointly by the operating system kernel's terminal driver and bash.

用户一般在交互的人机界面中使用这种功能。界面是由系统的终端驱动和 bash 共同提供的。

上面可以看错需要有界面才能控制,那在脚本里面有可能调用吗?继续往下查找JOB关键字,可以看到有一个set -m参数,可以设置monitor模式

-m Monitor mode. Job control is enabled. This option is on by default for interactive shells on systems that support it (see JOB CONTROL above). Background processes run in a separate process group and a line containing their exit status is printed upon their completion.

monitor模式。作业控制被启用。在支持这个选项的系统中,它在交互 shell中是默认启用的 (参见上面的 JOB CONTROL 作业控制)。后台进程在单独的进程组中运行,结束时将打印出包含它们退出状态的一行信息。

修改后的脚本

#!/bin/bash

set -m

/opt/nginx/sbin/nginx -g "daemon off;" &

PORT=$(ss -lntpd | grep '\"nginx\"' | awk '{split($5,a,":");print a[2]}'|head -n 1)

/nginx-monitor &

fg 1 >> /data/startup.log 2>&1

标签: #nginx挂掉原因