Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #include <sys/mman.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <semaphore.h>
- #define AANTAL_PROCS 200
- struct inf_t {
- sem_t sem[2];
- int numbers[AANTAL_PROCS];
- pid_t pid[AANTAL_PROCS];
- int max_number;
- int max_proc;
- };
- int main(int argc, char **argv){
- struct inf_t *inf;
- int fd=shm_open("myshm",O_CREAT|O_RDWR, S_IRWXU);
- ftruncate(fd,sizeof(struct inf_t));
- inf=mmap(NULL,sizeof(struct inf_t),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
- sem_init(&(inf->sem[0]),1,0);
- sem_init(&(inf->sem[1]),1,AANTAL_PROCS);
- int i;
- for (i=0;i<AANTAL_PROCS;i++){
- if ( (inf->pid[i]=fork())<0){
- perror(argv[0]);
- exit(1);
- }
- else if (inf->pid[i]==0){
- srand(getpid());
- inf->pid[i]=getpid();
- inf->numbers[i]=rand()%5000;
- sem_wait(&(inf->sem[1]));
- // printf("%d is waiting\n",inf->pid[i]);
- sem_wait(&(inf->sem[0]));
- if (inf->max_number==inf->numbers[i]){
- printf("Process %d: %s\n",inf->pid[i],"I'm the winner");
- }
- else {
- printf("Process %d: %d is the winner\n",inf->pid[i],inf->pid[inf->max_proc]);
- }
- sem_post(&(inf->sem[0]));
- exit(0);
- }
- }
- int value;
- sem_getvalue(&(inf->sem[1]),&value);
- while(value>0){
- sem_getvalue(&(inf->sem[1]),&value);
- }
- inf->max_number=inf->numbers[0];
- inf->max_proc=0;
- for(i=1;i<AANTAL_PROCS;i++){
- if (inf->numbers[i]>inf->max_number){
- inf->max_number=inf->numbers[i];
- inf->max_proc=i;
- }
- }
- sem_post(&(inf->sem[0]));
- for(i=0;i<AANTAL_PROCS;i++){
- int status;
- waitpid(inf->pid[i],&status,0);
- }
- munmap(inf,sizeof(struct inf_t));
- return 0;
- }
Add Comment
Please, Sign In to add comment