Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdio.h"
- #include "unistd.h"
- #include "pthread.h"
- #include "stdlib.h"
- #include "errno.h"
- #include "limits.h"
- #include "math.h"
- #include "semaphore.h"
- #include "string.h"
- #define BUFFER_SIZE 100
- #define PREFIX "MARCIN"
- sem_t doZapisu, doOdczytu;
- void emptyBuffer( char* buff);
- void emptyNBuffer( char* buff, int n);
- void *threadCzytelnik(void *arg);
- struct targs{
- int numWatku;
- };
- char common[BUFFER_SIZE];
- int koniecPliku = 0;
- int main()
- {
- FILE *fp;
- emptyBuffer(common);
- sem_init(&doZapisu, 0, 1);
- sem_init(&doOdczytu, 0, 0);
- pthread_attr_t attrs;
- pthread_attr_init(&attrs);
- pthread_attr_setdetachstate(&attrs,
- PTHREAD_CREATE_DETACHED );
- pthread_t threadId[3];
- fp = fopen("/etc/passwd","r");
- struct targs numery[3];
- {
- int i = 0;
- for(;i < 3; i++)
- {
- numery[i].numWatku = i+1;
- pthread_create(&threadId[i], &attrs, threadCzytelnik, &numery[i]);
- }
- }
- while( 1 ) {
- sem_wait(&doZapisu);
- emptyBuffer(common);
- char *ile = fgets(common, BUFFER_SIZE, fp);
- if( ile==NULL ) break;
- sem_post(&doOdczytu);
- //printf("%s\n", common);
- //emptyBuffer(common);
- }
- fclose(fp);
- koniecPliku = 1;
- sem_post(&doOdczytu);
- sem_post(&doOdczytu);
- sem_post(&doOdczytu);
- }
- void emptyBuffer( char* buff)
- {
- {
- int i = 0;
- for(;i<BUFFER_SIZE;i++)
- {
- buff[i] = 0;
- }
- }
- }
- void emptyNBuffer( char* buff, int n)
- {
- {
- int i = 0;
- for(;i<n;i++)
- {
- buff[i] = 0;
- }
- }
- }
- void *threadCzytelnik(void *arg)
- {
- struct targs *argptr = (struct targs*) arg;
- char nazwaPliku[80];
- snprintf(nazwaPliku, 80, "./MARCIN%d", argptr->numWatku);
- FILE *fp = fopen(nazwaPliku, "w");
- while(1)
- {
- sem_wait(&doOdczytu);
- if(koniecPliku)
- {
- fflush(fp);
- fclose(fp);
- pthread_exit(0);
- }
- fwrite(common, sizeof(char), strlen(common), fp);
- printf("%d-%s\n", argptr->numWatku, common);
- fflush(stdout);
- sem_post(&doZapisu);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement