Use a threaded program to do the same .
Here I am handling the input in the main thread and calling the function in a loop in another function which runs on its own thread until key is pressed.
Here , I am using mutex lock to handle synchronisation .
Suppose the Program name is Test.c , then compile with -pthread flag "gcc Test.c -o test -pthread" without qoutes.
I am assuming you are using Ubuntu.
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
pthread_mutex_t tlock=PTHREAD_MUTEX_INITIALIZER;
pthread_t tid;
int keypressed=0;
void function()
{
printf("\nInside function");
}
void *threadFun(void *arg)
{
int condition=1;
while(condition)
{
function();
pthread_mutex_lock(&tlock);
if(keypressed==1)//Checking whether Enter input has occurred in main thread.
condition=0;
pthread_mutex_unlock(&tlock);
}
}
int main()
{
char ch;
pthread_create(&tid,NULL,&threadFun,NULL);//start threadFun in new thread
scanf("%c",&ch);
if(ch=='\n')
{
pthread_mutex_lock(&tlock);
keypressed=1;//Setting this will cause the loop in threadFun to break
pthread_mutex_unlock(&tlock);
}
pthread_join(tid,NULL);//Wait for the threadFun to complete execution
return 0;
}
You may have to perform the scanf() and checking in a loop if you expect other characters to be input.