Can I interrupt a function if it takes too long?

I have a third-party function that I use in my program. I cannot replace him; it is in a dynamic library, so I also cannot edit it. The problem is that it sometimes works too long.

So, can I do anything to stop this function from running if it has been running for more than 10 seconds? (OK to close the program in this scenario.)

PS. I have Linux, and this program does not need to be ported anywhere.

I want something like this:

#include <stdio.h>
#include <stdlib.h>

void func1 (void) // I can not change contents of this.
{
  int i; // random
  while (i % 2 == 0);
}

int main ()
{
  setTryTime(10000);
  timeTry{
     func1();
  } catchTime {
     puts("function executed too long, aborting..");
  }

  return 0;
}
+3
source share
3 answers

Of course. And you will do it exactly as you suggested in your name: “signals”.

In particular, the alarm:

+3

, , , , , . , .

, ( , ) , , , , .

+3

, "" , . , , :

  • ( )

, (, fork) . . , - , , , .

, - , . , : , , , func1(), , .

, kill() , pthread_kill, func1() , , - pthread_cancel, .

0

All Articles