![为什么我的 bash 脚本会被“杀死”?我该如何防止这种情况发生?](https://linux22.com/image/894055/%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E7%9A%84%20bash%20%E8%84%9A%E6%9C%AC%E4%BC%9A%E8%A2%AB%E2%80%9C%E6%9D%80%E6%AD%BB%E2%80%9D%EF%BC%9F%E6%88%91%E8%AF%A5%E5%A6%82%E4%BD%95%E9%98%B2%E6%AD%A2%E8%BF%99%E7%A7%8D%E6%83%85%E5%86%B5%E5%8F%91%E7%94%9F%EF%BC%9F.png)
我编写了一个 bash 脚本,用于根据测试套件测试学生编写的 C 程序。由于某种原因,该脚本在一段时间后被终止。我是 bash 脚本编写的新手,到现在还没有找到原因。这是脚本。
#!/bin/bash
ulimit -t 1
tests_dir=tests
run_dir=tests
find . -name "*.c" | while read cfile; do rm a.out &> /dev/null; gcc "$cfile" -lm -w &> /dev/null;
if [ ! -f a.out ];
then
echo "$cfile did-not-compile" >> "$run_dir/results.out";
else
find "$tests_dir" -name "in*.txt" | while read testin; do echo "running $testin on $cfile";
rm test.out &> /dev/null;
rm space_less_testout &> /dev/null;
LD_PRELOAD=../../EasySandbox/EasySandbox.so ./a.out < $testin | grep -v "entering SECCOMP mode" &> test.out;
if [ -e test.out ]; then
testout=${testin/in/out}
tr -d '\n' < $testout | tr -d ' ' > space_less_testout
echo -e '\n' >> space_less_testout
if diff -qwB "$testout" test.out &> /dev/null
then
# if no difference then takes true brance (based on return value)
echo "$cfile ;passed-on-test; $testin" >> "$run_dir/results.out"; echo "passed-on-test $testin";
elif diff -qB space_less_testout test.out &> /dev/null
then
# or no difference with new-line removed should-be-output (just a formatting error)
echo "$cfile ;passed-on-test; $testin" >> "$run_dir/results.out"; echo "passed-on-test $testin";
else
echo "$cfile ;failed-on-test; $testin" >> "$run_dir/results.out"; echo "failed-on-test $testin";
fi
fi
done;
fi
done;
答案1
ulimit -t 1
将脚本的 CPU 时间限制为 1 秒。当脚本消耗完所有 CPU 时间后,就会被终止。
要限制脚本中某个命令的 CPU 时间,可以使用括号在子 shell 中启动该命令,并设置其自己的限制,例如
(ulimit -t 1; LD_PRELOAD=../../EasySandbox/EasySandbox.so ./a.out < $testin)