Hi Experts,
I have a programming assignment that asks us to implement a pipegrep function. it basically has 5 stages and each stage has a thread and buffers are used between stages.
am currently implementing stage 1 . In stage 1 am suppose to read directory and store the filenames in buffer1 shared with stage2 which applies filter like filesize etc,eg: it puts the files having filesize > 4096 into buffer2.I have implemented but am facing problems , am getting desired out put sometime but most of the times it doesnt work as required.
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<dirent.h>
#include<semaphore.h>
#include<pthread.h>
char *buffer1[10];
char *buffer2[10];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t empty,full;
void *stage1();
void *stage2();
int main(){
pthread_t thrd1,thrd2;
sem_init(&empty, 0, 10);
sem_init(&full,0,0);
int tid1 = pthread_create(&thrd1,NULL,&stage1,(void *)0);
if(tid1 == -1)
perror("cant create thread \n");
int tid2 = pthread_create(&thrd2,NULL,&stage2,(void *)0);
if(tid2 == -1)
perror("cant create thread \n");
pthread_join(thrd1, NULL);
pthread_join(thrd2, NULL);
//getchar();
pthread_exit(NULL);
}
void *stage1(){
//printf("Inside thread 1 \n");
DIR *directory;
struct dirent *dir;
int in;
directory = opendir(".");
in=0;
while((dir=readdir(directory))!=NULL){
if (strcmp(dir->d_name, ".") == 0|| strcmp(dir->d_name, "..")==0)
continue;
sem_wait(&empty);
//printf("buffer is not empty \n");
pthread_mutex_lock(&mutex);
//printf("thread 1 got access \n");
/* if got access enter filename into buffer */
buffer1[in]=dir->d_name;
//printf(" ^%s^ \n",buffer1[in]);
in=(in+1)%10;
sem_post(&full);//indicate consumer filename is available
pthread_mutex_unlock(&mutex);
}
closedir(directory);
pthread_exit(NULL);;
}
void *stage2(){
//printf("Inside thread2 also \n");
int out =0 ;
int in = 0;
struct stat sb;
int fsize = 4096;
int s=0;
while(s != -1){
//printf("File = %s ,File size = %d \n",buffer,(int)sb.st_size);
sem_wait(&full);
//printf("buffer is full goin ahead\n");
pthread_mutex_lock(&mutex);
//printf("thread2 got access \n");
s=stat(buffer1[out],&sb);
if(sb.st_size > fsize){
buffer2[in] = buffer1[out];
printf(" file = %s and size = %d \n",buffer2[in],(int)sb.st_size);
out = (out+1)%10;
in = (in+1)%10;
sem_post(&empty);
pthread_mutex_unlock(&mutex);
}
else {
out = (out+1)%10;
pthread_mutex_unlock(&mutex);
}
}
pthread_exit(NULL);
}
O/p:
ameya@ameya-Dell-System-Inspiron-N4110:~/os_concepts/Advanced_shell$ ./listfiles
file = advanced_shell.c~ and size = 11141
file = advanced_shell and size = 16693
file = listfiles and size = 7919
file = advanced_shell.c and size = 10840
program stuck here, i have closed the directory as well
Please check and provide u r feedback.
Regards,
Ameya