기본적으로
nohup <command> 2>&1 >> log.txt &
라고 입력하면, 표준 에러(2)를 표준 출력(1)으로 리다이렉트시키고, 그것을 log.txt에 append하여 실행한 command의 프로세스가 쉘 종료 뒤에도 계속 남아있게끔 해준다. 또한, echo $!를 하면 방금 nohup &으로 실행한 백그라운드 프로세스의 PID를 알아낼 수 있다. 이를 응용하면 아래와 같은 bash script를 작성할 수 있다.
#!/bin/bash
is_running=0
if [ -s pid.txt ];
then
running_pid=`cat pid.txt`
if ps -p $running_pid > /dev/null
then
is_running=1
fi
fi
if [ a$1 == ak ];
then
if [ $is_running == 0 ];
then
echo no running program found
else
kill $running_pid
echo killed $running_pid
fi
exit 0
fi
if [ $is_running == 0 ];
then
nohup sleep 10 2>&1 >> log.txt &
echo $! > pid.txt
echo program started on pid $!
else
echo program is already running on pid $running_pid
fi
위 bash script 파일명을 nsleep이라 한다면...
./nsleep을 입력하면 프로세스가 존재하지 않을 경우 sleep 10을 백그라운드에서 실행한다.
./nsleep k를 입력하면 프로세스가 존재할 경우 저장한 PID의 프로세스를 죽인다.
References
https://stackoverflow.com/questions/3043978/how-to-check-if-a-process-id-pid-exists
How to check if a process id (PID) exists
In a bash script, I want to do the following (in pseudo-code): if [ a process exists with $PID ]; then kill $PID fi What's the appropriate expression for the conditional statement?
stackoverflow.com
[Linux] 백그라운드 실행하기 : &와 nohup
리눅스 시스템에서 작업을 수행하다 보면, 긴 시간이 걸리는 명령어를 실행해야 할 때가 있다. 그러나 터미널을 닫거나 세션이 끊기면 작업이 종료되는 문제가 생길 수 있다. 이를 방지하기 위
nayoungs.tistory.com