我们可以在几秒钟后强制退出C程序的执行

时间:2012-02-10 06:38:18

标签: php c gcc cygwin

我们可以在几分之一秒(毫秒范围)或它使用的内存大小后强制退出C程序的执行吗?这样,我想在无限循环中限制打印内容并限制缓冲区溢出。

我正在使用cygwin GCC4.3编译器,并希望将其作为PHP中的工具实现,它将C源作为输入并显示相应的输出。

PS - 我说毫秒,因为我的C问题只涉及非常简单的算术/计算。 2.为了限制执行时间,php中的set_time_limit()将限制整个PHP脚本的执行时间,而不是分配给exec()的时间

4 个答案:

答案 0 :(得分:2)

您可能想要调查您的系统是否具有来自POSIX 2008的nanosleep()。请注意,即使您可以指定以纳秒为单位的时间,系统也可能无法非常可靠地遵循亚毫秒时序。

您可能会发现µ-sleep()(拼写为usleep())可用,但它已正式废弃。它指定一个包含微秒的时间。在Google上快速搜索“usleep windows”会将Sleep()建议为Windows本机替代版。

另请参阅:Sleep less than one millisecond

另见:Command line command to auto-kill a command after a certain amount of time。目前没有编写处理亚秒级时序的程序,但是一旦你决定使用亚秒级时序接口,必要的改编就不会很难。

答案 1 :(得分:1)

您应该能够使用alarm()函数。虽然它在unistd.h中找到,但它是一个POSIX.1-2001函数,应该在cygwin下可用。如果未处理SIGALRM,则会终止该过程。

试一试:

#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 */
}

更新

正如jonathan指出警报(2)仅在几秒钟内工作所以你可以使用setitimer(也符合POSIX)

#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 HERE--复制到--END CUT--并将其粘贴到您的主文件中;

更新2

限制内存尝试使用setrlimit:

请参阅Set stack size with setrlimit() and provoke a stack overflow/segfault

示例

答案 2 :(得分:0)

我过去做过类似的事情,我使用的架构是 - 有一个父C程序说main.c,代码类似于下面(注意这不是一个生产代码,甚至不保证编译,下面的代码只是为了演示的目的)。

// ---------------------- main.c ----------------
int main_child(); // the body is defined in "your_test_source.c"

int main()
{
  pthread_t tid;

  // create child thread
  pthread_create(tid, NULL, main_child, NULL);

  // start monitoring the child thread
  // ...
  // you can kill child thread by calling pthread_exit
  // and check for memory usage by system calls.

  return 0;
}

#define main main_child
  // we change the main function to main_child
  #include "your_test_source.c"
#undef main
// ---------------------- end -------------

your_test_source.c - 这是测试文件。

这为您编译和调试添加了一个层,但它可以工作。

答案 3 :(得分:0)

要限制内存大小,请不要使用动态内存分配或递归。然后,您可以确保内存要求是有界的(这是安全关键系统的编码标准)。

至于时间要求,为什么只能忍受秒的粒度和限制执行到一秒?