我们可以强制秒钟的一小部分后,退出一个C程序的执行 [英] Can we force quit a C program's execution after a fraction of seconds
问题描述
我们能迫使秒(毫秒范围)的一小部分后,退出一个C程序的执行或者通过它使用内存的大小?这样的话,我想限制在一个无限循环的打印内容和限制缓冲区溢出。
Can we force quit a C program's execution after a fraction of seconds (range of milliseconds) or by the size of memory it uses? This way, I want to restrict printing content in an infinite loop and restrict buffer overruns.
我使用的cygwin GCC4.3编译器和要实现它作为PHP的一个工具,这需要在C源代码作为输入并显示相应的输出。
I am using cygwin GCC4.3 compiler and want to implement it as a tool in PHP, which takes in the C source as input and displays the corresponding output.
PS -
1.我说毫秒,因为我的C问题只会涉及到非常简单的算术/计算。
2.要限制的执行时间,在php set_time_limit()函数将限制整个PHP脚本的执行时间,而不是分配给执行的是时间()
PS - 1. I say milliseconds because my C problems will only involve very simple arithmetic/computations. 2. To restrict the execution time, set_time_limit()in php would restrict the entire PHP script's execution time and not the time allotted to exec( )
推荐答案
您应该能够使用报警()函数。而它是在unistd.h中发现它是一个POSIX.1-2001函数,并应在cygwin下可用。如果SIGALRM不处理它杀死的过程。
You should be able to use the alarm() function. While it is found in unistd.h it is a POSIX.1-2001 function and should be available under cygwin. If SIGALRM is not handled it kills the process.
试试吧:
#include <stdio.h>
#include <unistd.h>
int main() {
alarm(5); /* raise alarm after 5 seconds */
while(1) {
printf("Running forever\n");
}
return 0; /* never reached */
}
更新
乔纳森指出的报警(2)只有在几秒钟内工作,所以你可以再使用setitimer,而不是(也POSIX兼容)
update
As jonathan points out alarm(2) only works in seconds so you can use setitimer instead (also POSIX compliant)
#include <stdio.h>
#include <sys/time.h>
int main() {
/* --CUT HERE-- */
struct itimerval timer;
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 5000; /* 5 milliseconds */
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
setitimer(ITIMER_REAL, &timer, NULL);
/* --END CUT-- */
while(1) {
printf("Running forever\n");
}
return 0; /* never reached */
}
如果您的系统上的上述作品,
从--Cut这里 - 副本code到--End CUT--并粘贴到你的主;
if the above works on your system, copy code from --CUT HERE-- to --END CUT-- and paste it into your main;
要限制内存尝试使用了setrlimit:
to limit memory try using setrlimit:
看<一个href=\"http://stackoverflow.com/questions/4118016/set-stack-size-with-setrlimit-and-provoke-a-stack-overflow-segfault\">Set堆栈通过setrlimit大小(),并引发一个堆栈溢出/段错误
为例
这篇关于我们可以强制秒钟的一小部分后,退出一个C程序的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!