Search code examples
phpcgcccygwin

Can we force quit a C program's execution after a fraction of seconds


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.

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. 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( )


Solution

  • 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.

    Try it:

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

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

    if the above works on your system, copy code from --CUT HERE-- to --END CUT-- and paste it into your main;

    update 2

    to limit memory try using setrlimit:

    see Set stack size with setrlimit() and provoke a stack overflow/segfault

    for an example