crontab이 이상하게 행동합니다

crontab이 이상하게 행동합니다

그럼 내 마지막 질문을 토대로여기작동하게 되었지만 2분마다 특정 날짜의 행 수를 확인하는 crontab을 만들어 보았습니다.

내 스크립트는 다음과 같습니다

1 test=/root/test
2 n="$(cat /root/test)"
3 t="$(date)"
4 echo "there were $n lines in $test at $t" >> rtest1

스크립트를 실행할 때마다 rtest1은 원하는 결과를 보여줍니다.

there were 224 lines in /root/test at Fri Aug 10 10:28:25 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:25 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:26 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:26 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:26 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:28:26 EEST 2018

그러나 crontab으로 인해 이런 일이 발생하면 이상한 이유로 다음과 같이 줄 번호가 생략되는 경우가 있습니다.

there were 229 lines in /root/test at Fri Aug 10 10:20:51 EEST 2018
there were  lines in /root/test at Fri Aug 10 10:22:01 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:24:01 EEST 2018
there were 224 lines in /root/test at Fri Aug 10 10:26:02 EEST 2018
there were  lines in /root/test at Fri Aug 10 10:28:01 EEST 2018

내 crontab은 다음과 같습니다.

[root@centos7desk ~]# crontab -l
* * * * * ps axu | wc -l > /root/test
*/2 * * * * /root/script.sh

왜 이런 일이 발생하는지 모르겠습니다.

답변1

기본적으로 두 개의 crontab 항목이 동시에 실행되면 이는 경쟁 조건입니다. "값 없음"의 경우 출력 파일이 생성되지만 아직 채워지지 않습니다( ps axu | wc -l런타임이 스크립트보다 길 수 있기 때문).

이 문제를 극복하기 위해 sleep 5스크립트 시작 부분에 를 추가할 수 있습니다. (기술적으로 이렇게 하면 경쟁 조건이 방지되지는 않지만 시스템 부하가 심한 경우가 아니면 발생할 가능성이 낮습니다.) 아니면 모든 것을 스크립트에 넣습니다(이것이 더 나은 솔루션일 수 있습니다).

관련 정보