Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <signal.h>
- #include <sys/wait.h>
- #include <sys/mman.h>
- #include <sys/types.h>
- #include <unistd.h>
- void SIGUSR1_handler(int);
- void SIGUSR2_handler(int);
- int receive1 = 0;
- int receive2 = 0;
- static int *scorePlayer1;
- static int *scorePlayer2;
- int main(int argc, char const *argv[])
- {
- int frappe = 0;
- srand(time(NULL));
- scorePlayer1 = mmap(NULL,sizeof *scorePlayer1,PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS, -1, 0); //Memoire partagée entre les process
- *scorePlayer1 = 0;
- scorePlayer2 = mmap(NULL,sizeof *scorePlayer2,PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS, -1, 0);
- *scorePlayer2 = 0;
- signal(SIGUSR1,SIGUSR1_handler);
- signal(SIGUSR2,SIGUSR2_handler);
- pid_t pid = fork(); //Create child process
- switch (pid)
- {
- case 0: //Fils
- while(*scorePlayer1 <=13 && *scorePlayer2 <= 13)
- {
- while(receive1 ==0) //Permet de synchroniser les process
- {}
- if(*scorePlayer2 == 13)
- {
- printf("J'ai gagné ! pourquoi ai-je un pere aussi nul ?\n");
- fflush(stdout);
- kill(getppid(),SIGTERM);
- exit(EXIT_SUCCESS);
- }
- frappe = (rand() % 100);
- if(frappe < 50) //Reussi son coup
- {
- }
- else //Loupe la balle
- {
- printf("Le joueur fils loupe sa frappe, le pere gagne 1 point\n");
- fflush(stdout);
- *scorePlayer1 = *scorePlayer1 +1;
- printf("Score actuel %d (pere) à %d (fils) \n",*scorePlayer1,*scorePlayer2);
- fflush(stdout);
- }
- printf("PONG \n");
- fflush(stdout);
- *compteur = *compteur +1;
- receive1 = 0;
- sleep(1);
- kill(getppid(),SIGUSR2);
- }
- break;
- default: //Pere
- receive2 = 1;
- printf("Le pere engage le match\n");
- fflush(stdout);
- while(*scorePlayer1 <= 13 && *scorePlayer2 <= 13)
- {
- while(receive2 == 0) //Permet de synchroniser les process
- {}
- if(*scorePlayer1 == 13)
- {
- printf("J'ai gagné ! pourquoi ai-je fait un enfant aussi nul ?\n");
- fflush(stdout);
- kill(pid,SIGTERM);
- exit(EXIT_SUCCESS);
- }
- frappe = (rand() % 100);
- if(frappe < 50) //Reussis son coup
- {
- }
- else //Rate la balle
- {
- printf("Le joueur pere loupe sa frappe, le fils gagne 1 point\n");
- fflush(stdout);
- *scorePlayer2 = *scorePlayer2 +1;
- printf("Score actuel %d (pere) à %d (fils) \n",*scorePlayer1,*scorePlayer2);
- fflush(stdout);
- }
- printf("PING \n");
- fflush(stdout);
- receive2 = 0;
- sleep(1);
- kill(pid,SIGUSR1);
- }
- break;
- }
- return 0;
- }
- void SIGUSR1_handler(int signum)
- {
- if(signum == SIGUSR1)
- {
- receive1 = 1;
- }
- }
- void SIGUSR2_handler(int signum)
- {
- if(signum == SIGUSR2)
- {
- receive2 = 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment