簡體   English   中英

在調用者腳本結束時結束的 shell 腳本

[英]shell scripts that's ends when the caller script end

我有兩個腳本:/mnt/tmp/a.sh:

#!/bin/bash

echo hello >> /tmp/a.sh.log
i=0
/mnt/tmp/b.sh &

while [[ $i -lt "5" ]]
do
        echo "seconde : $i " >> /tmp/a.sh.log
        sleep 1
        i=$(($i+1))
done

和/mnt/tmp/b.sh

#!/bin/bash

echo hello >> /tmp/b.sh.log
i=0

while [[ $i -lt "10" ]]
do
        echo "seconde : $i " >> /tmp/b.sh.log
        sleep 1
        i=$(($i+1))
done

當我手動啟動 /mnt/tmp/a.sh 時,這里是輸出文件:/tmp/a.sh.log

hello
seconde : 0
seconde : 1
seconde : 2
seconde : 3
seconde : 4

和/tmp/b.sh.log

hello
seconde : 0
seconde : 1
seconde : 2
seconde : 3
seconde : 4
seconde : 5
seconde : 6
seconde : 7
seconde : 8
seconde : 9

但是當 /mnt/tmp/a.sh 在系統啟動期間被調用時,這里是輸出文件:

/tmp/a.sh.log

hello
seconde : 0
seconde : 1
seconde : 2
seconde : 3
seconde : 4

和 /tmp/b.sh.log 你好

seconde : 0
seconde : 1
seconde : 2
seconde : 3
seconde : 4

當 /mnt/tmp/a.sh 結束時,它在后台啟動的所有腳本(使用 &)結束!

a.sh 腳本在啟動時由 /usr/bin/custom-script 調用:

#!/bin/bash


echo "===========================================" > /tmp/start
echo "        custom script                      " >> /tmp/start
echo "===========================================" >> /tmp/start

mount /dev/mmcblk0p1 /mnt
/mnt/tmp/a.sh

這個自定義腳本由 /lib/systemd/system/custom-script.service 配置為:

[Unit]
Description=start custom script at boot

[Service]
Type=simple
ExecStart=/bin/sh -c '/usr/bin/custom-script'

[Install]
WantedBy=multi-user.target

我正在使用基於 yocto 的系統在 SOM 板 imx6 中工作。

已經嘗試過的解決方法:

所有這些版本的 /mnt/tmp/a.sh 都有同樣的問題:

使用執行:

#!/bin/bash

echo hello >> /tmp/a.sh.log
i=0
(exec /mnt/tmp/b.sh )&

while [[ $i -lt "5" ]]
do
        echo "seconde : $i " >> /tmp/a.sh.log
        sleep 1
        i=$(($i+1))
done

使用來源:

#!/bin/bash

echo hello >> /tmp/a.sh.log
i=0
source /mnt/tmp/b.sh &

while [[ $i -lt "5" ]]
do
        echo "seconde : $i " >> /tmp/a.sh.log
        sleep 1
        i=$(($i+1))
done

使用 nohup:

#!/bin/bash

echo hello >> /tmp/a.sh.log
i=0
nohup /mnt/tmp/b.sh > /var/log/nohup.log & # I used /var/log/nohup.log because my system is read-only:nohup: can't open '/home/root/nohup.out': Read-only file system 

while [[ $i -lt "5" ]]
do
        echo "seconde : $i " >> /tmp/a.sh.log
        sleep 1
        i=$(($i+1))
done

有人可以在這里幫忙嗎?

我只是解決了這個問題:

自定義腳本的 systemd 服務文件應該有 type=forking 而不是 type=simple:

/lib/systemd/system/custom-script.service

[Unit]
Description=start custom script at boot

[Service]
Type=forking
ExecStart=/usr/bin/custom-script

[Install]
WantedBy=multi-user.target

謝謝你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM