Advertisement
LazySenpai

zad3

Dec 10th, 2019
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6.  
  7. char mutual[100];
  8. int flag[2];
  9. int thread_id[2];
  10. pthread_mutex_t lock;
  11.  
  12. void* read_thread(void *arg) {
  13. char *file_name = (char *)arg;
  14. int thread_number;
  15. if(file_name == "/etc/profile")
  16. thread_number=0;
  17. else
  18. thread_number=1;
  19.  
  20. thread_id[thread_number]=pthread_self();
  21.  
  22. FILE* input=fopen(file_name,"r");
  23.  
  24. while(1) {
  25. pthread_mutex_lock(&lock);
  26. if(!fgets(mutual, 100, input)){
  27. flag[thread_number]= (-1);
  28. pthread_mutex_unlock(&lock);
  29. break;
  30. }
  31. else{
  32. flag[thread_number]=1;
  33. }
  34. while(flag[thread_number]==1)
  35. usleep(100);
  36. pthread_mutex_unlock(&lock);
  37. usleep(100);
  38. }
  39. }
  40.  
  41. int main() {
  42. flag[0]=0;
  43. flag[1]=0;
  44. pthread_t reader[2];
  45. char *prof = "/etc/profile";
  46. char *pass = "/etc/passwd";
  47. FILE *fp[2];
  48. fp[0] = fopen("./KACPER1", "w");
  49. fp[1] = fopen("./KACPER2", "w");
  50.  
  51. if (pthread_mutex_init(&lock, NULL) != 0) {
  52. printf("\n mutex init has failed\n");
  53. return 1;
  54. }
  55.  
  56. pthread_create(&reader[0], NULL, &read_thread, (void *)prof);
  57. pthread_detach(reader[0]);
  58. pthread_create(&reader[1], NULL, &read_thread, (void *)pass);
  59. pthread_detach(reader[1]);
  60.  
  61. while(1){
  62. if(flag[0] == 1) {
  63. fwrite(mutual, sizeof(char), 100, fp[0]);
  64. printf("%d : %s", thread_id[0], mutual);
  65. memset(mutual,0,100);
  66. flag[0] = 0;
  67. }
  68. if(flag[1] == 1) {
  69. fwrite(mutual, sizeof(char), 100, fp[1]);
  70. printf("%d : %s", thread_id[1], mutual);
  71. memset(mutual,0,100);
  72. flag[1] = 0;
  73. }
  74. if(flag[0] == -1 && flag[1] == -1)
  75. break;
  76. usleep(100);
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement