Each time timer expires the flag will be raised, and a thread will be created to do some special task, and let the main task continue its task without any interruption (as I have shown in Expected Output:). But as you can see in the Actual Output, when the thread is created the main task is stopped, though the thread takes very large time (more than 20 sec) to complete. Since the main thread is in an infinite loop (though it is switching between functions), I don't think I should use pthread_join(). What is Happening, and what should I do to get the expected output?
int global_flag, thread_exist;
void main() {
//background time, on timer expire, execute "timer_signal_handler"
create_timer(tim_value=60sec, tim_interval=60sec);
int val = 0;
while(1){
val = random_integer_generator();
function_fun(val);
}
return;
}
void function_fun(int val) {
if(global_flag == 1 && thread_exist == 0) {
global_flag = 0;
pthread_t pid_port_scan;
if ((pthread_create (&pid_port_scan, NULL, portScanRoutine, NULL)) != 0) {
perror("pthread_create: ");
thread_exist = 0;
exit(EXIT_FAILURE);
}
else thread_exist = 1;
}
printf("value %d\n", val);
return;
}
void *portScanRoutine(void* ptr) {
printf("started scanning...\n");
printf("scanning in progress...\n");
scan_for_ports_whick_takes_around_20_to_30_seconds;
printf("done scanning...\n");
thread_exist = 0;
return;
}
void timer_signal_handler(int sigId) {
printf("timer expied\n");
global_flag = 1;//set to indicate
}
actual Output:
value x//x is random value
value x
value x
value x
value x
value x
timer expied
started scanning...
scanning in progress...
done scanning...
value x
value x
value x
value x
value x
timer expied
started scanning...
scanning in progress...
done scanning...
value x
value x
value x
expected output:
value x//x is random value
value x
value x
value x
value x
value x
timer expied
started scanning...
scanning in progress...
value x
value x
value x
value x
value x
value x
done scanning...
value x
value x
value x