Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <stdlib.h>
- char mutual[100];
- int flag[2];
- int thread_id[2];
- pthread_mutex_t lock;
- void* read_thread(void *arg) {
- char *file_name = (char *)arg;
- int thread_number;
- if(file_name == "/etc/profile")
- thread_number=0;
- else
- thread_number=1;
- thread_id[thread_number]=pthread_self();
- FILE* input=fopen(file_name,"r");
- while(1) {
- pthread_mutex_lock(&lock);
- if(!fgets(mutual, 100, input)){
- flag[thread_number]= (-1);
- pthread_mutex_unlock(&lock);
- break;
- }
- else{
- flag[thread_number]=1;
- }
- while(flag[thread_number]==1)
- usleep(100);
- pthread_mutex_unlock(&lock);
- usleep(100);
- }
- }
- int main() {
- flag[0]=0;
- flag[1]=0;
- pthread_t reader[2];
- char *prof = "/etc/profile";
- char *pass = "/etc/passwd";
- FILE *fp[2];
- fp[0] = fopen("./KACPER1", "w");
- fp[1] = fopen("./KACPER2", "w");
- if (pthread_mutex_init(&lock, NULL) != 0) {
- printf("\n mutex init has failed\n");
- return 1;
- }
- pthread_create(&reader[0], NULL, &read_thread, (void *)prof);
- pthread_detach(reader[0]);
- pthread_create(&reader[1], NULL, &read_thread, (void *)pass);
- pthread_detach(reader[1]);
- while(1){
- if(flag[0] == 1) {
- fwrite(mutual, sizeof(char), 100, fp[0]);
- printf("%d : %s", thread_id[0], mutual);
- memset(mutual,0,100);
- flag[0] = 0;
- }
- if(flag[1] == 1) {
- fwrite(mutual, sizeof(char), 100, fp[1]);
- printf("%d : %s", thread_id[1], mutual);
- memset(mutual,0,100);
- flag[1] = 0;
- }
- if(flag[0] == -1 && flag[1] == -1)
- break;
- usleep(100);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement