如何使用 MinGW-Gnu C++ 编译具有限制时间(5 秒)的程序
How to compile a program with limit time (5s), using MinGW-Gnu C++
我知道如何用 GNU 编译程序,但有些程序可以在 "Infinity Loop" 中。目标是通过在某个给定时间间隔(称为 "Time litmit")后自动终止程序来避免程序中存在无限循环时的沮丧。 如何使用 GNU Makefile 来实现?
Example : Compile & running this code in 1s with n=10^10
int main()
{
int n =10000000000;
vector<int> a;
for (int i=0;i<n)
a.push(i);
return 0;
}
If program running over 1s, it's must be killed and i need a
"Time limited exceeded" notify.
抱歉英语不好:)
您可以使用 shell 和类似
的序列来完成
<program>&
pid=$!
sleep $time_limit
if ps aux | grep $pid | grep -v grep > /dev/null
then
kill $pid
echo "Time limit exceeded"
fi
这里有两个时间限制和没有时间限制的例子(使用sleep 10
和sleep 3
作为程序,时间限制为5秒):
$ sleep 10& pid=$!; sleep 5; if ps aux | grep $pid | grep -v grep > /dev/null; then kill $pid; echo "Time limit exceeded"; fi
Time limit exceeded
$ sleep 3& pid=$!; sleep 5; if ps aux | grep $pid | grep -v grep > /dev/null; then kill $pid; echo "Time limit exceeded"; fi
$
它的工作方式是程序在后台启动(在程序名称后加上 &
)。 pid ($!
) 存储在名为 pid
的变量中。然后我等待 $time_limit
使用 sleep 并检查 pid $pid
的进程是否仍在运行。我使用 | grep -v grep
因为 grep $pid
也会出现在 ps aux
.
的输出中
如果该进程仍在运行,我会终止它并显示您想要的消息。
这可以很容易地包含在 Makefile 中。如果您想在其他上下文中使用它,您也可以在 PATH
中将其设为 shell 脚本。
当您的程序挂起时,使用 ^C 中断它。然后,进入您的代码并找到问题所在。使用 GDB 之类的调试器单步执行代码并找到无限循环。我不确定自动终止程序的意义是什么,除了允许您多次 运行 它,尽管它已损坏。它是否生成了您需要的某种有意义的输出,而您只是不愿意找到错误?
我知道如何用 GNU 编译程序,但有些程序可以在 "Infinity Loop" 中。目标是通过在某个给定时间间隔(称为 "Time litmit")后自动终止程序来避免程序中存在无限循环时的沮丧。 如何使用 GNU Makefile 来实现?
Example : Compile & running this code in 1s with n=10^10
int main() { int n =10000000000; vector<int> a; for (int i=0;i<n) a.push(i); return 0; }
If program running over 1s, it's must be killed and i need a "Time limited exceeded" notify.
抱歉英语不好:)
您可以使用 shell 和类似
的序列来完成<program>&
pid=$!
sleep $time_limit
if ps aux | grep $pid | grep -v grep > /dev/null
then
kill $pid
echo "Time limit exceeded"
fi
这里有两个时间限制和没有时间限制的例子(使用sleep 10
和sleep 3
作为程序,时间限制为5秒):
$ sleep 10& pid=$!; sleep 5; if ps aux | grep $pid | grep -v grep > /dev/null; then kill $pid; echo "Time limit exceeded"; fi
Time limit exceeded
$ sleep 3& pid=$!; sleep 5; if ps aux | grep $pid | grep -v grep > /dev/null; then kill $pid; echo "Time limit exceeded"; fi
$
它的工作方式是程序在后台启动(在程序名称后加上 &
)。 pid ($!
) 存储在名为 pid
的变量中。然后我等待 $time_limit
使用 sleep 并检查 pid $pid
的进程是否仍在运行。我使用 | grep -v grep
因为 grep $pid
也会出现在 ps aux
.
如果该进程仍在运行,我会终止它并显示您想要的消息。
这可以很容易地包含在 Makefile 中。如果您想在其他上下文中使用它,您也可以在 PATH
中将其设为 shell 脚本。
当您的程序挂起时,使用 ^C 中断它。然后,进入您的代码并找到问题所在。使用 GDB 之类的调试器单步执行代码并找到无限循环。我不确定自动终止程序的意义是什么,除了允许您多次 运行 它,尽管它已损坏。它是否生成了您需要的某种有意义的输出,而您只是不愿意找到错误?