I want to write a program .its function very simple.
when I run it ,it will display some numbers. when I take some action such as press 's',it will pause until I press 'g'.
in short,I want to implement a function that the program can pause at any time,and continue.
I tried to use semaphore,but I failed.
reference the original code:
Code:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
void *thread_function(void *arg);
int worksize=10;
//char workarea[worksize];
char workarea[10];
sem_t sem;//critical
sem_t full;
sem_t empty;
int in=0,out=0;
int main()
{
int res;
FILE *fp;
int ch;
pthread_t a_thread;
void *thread_result;
/////////semaphore init////////
res=sem_init(&sem,0,1);
if(res!=0)
{perror("error:");exit(1);}
res=sem_init(&full,0,0);
if(res!=0)
{perror("error:");exit(1);}
res=sem_init(&empty,0,worksize);
if(res!=0)
{perror("error:");exit(1);}
/////////creat thread///////////
res=pthread_create(&a_thread,NULL,thread_function,NULL);
if(res!=0)
{perror("error:");exit(1);}
/////////open file/////////////
if((fp=fopen("/home/mirage/Desktop/program/pie.txt","r"))==NULL)
{perror("error:");exit(1);}
///////////producer-read from file////////////
while(1)
{
sem_wait(&empty);
sem_wait(&sem); //critical section
if((ch=fgetc(fp))==EOF)
break;
workarea[in]=ch;
in=(in+1)%worksize;//
sem_post(&sem); //no critical section
sem_post(&full);
}//while
sem_destroy(&sem);
sem_destroy(&empty);
sem_destroy(&full);
fclose(fp);
exit(0);
}//main
///////////consumer-output to terminal////////////
void *thread_function(void *arg)
{
int ent=0;
printf("pie=:3.\n");
while(1)
{
sem_wait(&full);
sem_wait(&sem); //critical section
usleep(80000);
printf("%c",workarea[out]);
fflush(stdout);
ent++;
if(ent==10)
{printf("\n");ent=0;}
out=(out+1)%worksize;
sem_post(&sem); //no critical section
sem_post(&empty);
}//while
}