Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/sem.h>
- #include <sys/shm.h>
- #include "semafori.h"
- #define SHM_KEY (key_t)1234
- #define SEM_KEY1 (key_t)5678
- #define SEM_KEY2 (key_t)9012
- #define TEXT_SIZE 2048
- char text[TEXT_SIZE];
- int main(int argc, char* argv[]){
- int continua=1;
- int ShmID;
- int SEM_USER_1, SEM_USER_2;
- void *ShmP=(void*)0;
- char *buf;
- int mySem;
- int yourSem;
- printf("Benvenuti nella chat, scrivi fine per terminare.\n");
- if (argc<2){
- ShmID = shmget(SHM_KEY, TEXT_SIZE, 0666 | IPC_CREAT);
- if(ShmID==-1){
- perror("errore di shmget");
- exit(EXIT_FAILURE);
- }
- ShmP= shmat(ShmID, (void *)0, 0);
- if(ShmP==(void *)-1){
- perror("errore shmat");
- exit(EXIT_FAILURE);
- }
- buf =(char *)ShmP;
- printf(buf, " ");
- SEM_USER_1=semget(SEM_KEY1, 1, 0666 | IPC_CREAT);
- if(SEM_USER_1==-1){
- perror("Errore semget 1");
- exit(EXIT_FAILURE);
- }
- SEM_USER_2=semget(SEM_KEY1, 1, 0666 | IPC_CREAT);
- if(SEM_USER_2==-1){
- perror("Errore semget 1");
- exit(EXIT_FAILURE);
- }
- if(SEM_SET(SEM_USER_2, 0)==-1) exit(EXIT_FAILURE);
- if(SEM_SET(SEM_USER_1, 1)==-1) exit(EXIT_FAILURE);
- mySem=SEM_USER_2;
- yourSem=SEM_USER_1;
- printf("Tu sei l'utente 2\n");
- } else
- {
- ShmID = shmget(SHM_KEY, TEXT_SIZE, 0666 | IPC_CREAT);
- if(ShmID==-1){
- perror("errore di shmget");
- exit(EXIT_FAILURE);
- }
- ShmP= shmat(ShmID, (void *)0, 0);
- if(ShmP==(void *)-1){
- perror("errore shmat");
- exit(EXIT_FAILURE);
- }
- buf=(char *) ShmP;
- SEM_USER_1=semget(SEM_KEY1, 1, 0666 | IPC_CREAT);
- if(SEM_USER_1==-1){
- perror("Errore semget 1");
- exit(EXIT_FAILURE);
- }
- SEM_USER_2=semget(SEM_KEY1, 1, 0666 | IPC_CREAT);
- if(SEM_USER_2==-1){
- perror("Errore semget 1");
- exit(EXIT_FAILURE);
- }
- mySem=SEM_USER_1;
- yourSem=SEM_USER_2;
- printf("Tu sei l'utente 1\n");
- }
- while (continua){
- SEM_P(mySem);
- if(strncmp(buf, "fine", 4)==0) continua=0;
- else{
- if(strlen(buf)>0)
- printf("Risposta: %s\n", buf);
- printf("> ");
- fgets(buf, TEXT_SIZE, stdin);
- if(strncmp(buf, "fine", 4)==0) continua=0;
- }
- SEM_V(yourSem);
- }
- if(mySem==SEM_USER_2){
- if(shmdt(ShmP)==-1){
- perror("Shmdt fallita\n");
- exit(EXIT_FAILURE);
- }
- if(shmctl(ShmID, IPC_RMID, 0) ==-1){
- perror("Shmctl errore");
- exit(EXIT_FAILURE);
- }
- SEM_DEL(SEM_USER_1);
- SEM_DEL(SEM_USER_2);
- }
- if(mySem==SEM_USER_1){
- if(shmdt(ShmP)==-1){
- perror("Shmdt fallita \n");
- exit(EXIT_FAILURE);
- }
- }
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement