Guest User

Untitled

a guest
Jun 23rd, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <fcntl.h>
  3. #include <sys/stat.h>
  4. #include <sys/mman.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <semaphore.h>
  10.  
  11. #define AANTAL_PROCS 200
  12.  
  13. struct inf_t {
  14. sem_t sem[2];
  15. int numbers[AANTAL_PROCS];
  16. pid_t pid[AANTAL_PROCS];
  17. int max_number;
  18. int max_proc;
  19. };
  20.  
  21. int main(int argc, char **argv){
  22. struct inf_t *inf;
  23. int fd=shm_open("myshm",O_CREAT|O_RDWR, S_IRWXU);
  24. ftruncate(fd,sizeof(struct inf_t));
  25. inf=mmap(NULL,sizeof(struct inf_t),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  26. sem_init(&(inf->sem[0]),1,0);
  27. sem_init(&(inf->sem[1]),1,AANTAL_PROCS);
  28. int i;
  29. for (i=0;i<AANTAL_PROCS;i++){
  30. if ( (inf->pid[i]=fork())<0){
  31. perror(argv[0]);
  32. exit(1);
  33. }
  34. else if (inf->pid[i]==0){
  35. srand(getpid());
  36. inf->pid[i]=getpid();
  37. inf->numbers[i]=rand()%5000;
  38. sem_wait(&(inf->sem[1]));
  39. // printf("%d is waiting\n",inf->pid[i]);
  40. sem_wait(&(inf->sem[0]));
  41. if (inf->max_number==inf->numbers[i]){
  42. printf("Process %d: %s\n",inf->pid[i],"I'm the winner");
  43. }
  44. else {
  45. printf("Process %d: %d is the winner\n",inf->pid[i],inf->pid[inf->max_proc]);
  46. }
  47. sem_post(&(inf->sem[0]));
  48. exit(0);
  49. }
  50. }
  51. int value;
  52. sem_getvalue(&(inf->sem[1]),&value);
  53. while(value>0){
  54. sem_getvalue(&(inf->sem[1]),&value);
  55. }
  56. inf->max_number=inf->numbers[0];
  57. inf->max_proc=0;
  58. for(i=1;i<AANTAL_PROCS;i++){
  59. if (inf->numbers[i]>inf->max_number){
  60. inf->max_number=inf->numbers[i];
  61. inf->max_proc=i;
  62. }
  63. }
  64. sem_post(&(inf->sem[0]));
  65. for(i=0;i<AANTAL_PROCS;i++){
  66. int status;
  67. waitpid(inf->pid[i],&status,0);
  68. }
  69. munmap(inf,sizeof(struct inf_t));
  70. return 0;
  71. }
Add Comment
Please, Sign In to add comment