Академический Документы
Профессиональный Документы
Культура Документы
AIM:
Program to implement Mutual Exclusion to share files using token based algorithm
PROGRAM CODE:
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
char buffer[MAXLINE];
printf("Initialising the server at port %d.\n", MY_PORT);
int sockfd = create_connection(MY_PORT);
char response[MAXLINE];
memset(&next_client_addr, 0, sizeof(next_client_addr));
next_client_addr.sin_family = AF_INET; // IPv4
next_client_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
next_client_addr.sin_port = htons(NEXT_CLIENT_PORT);
if (IS_INITIATOR) {
critical_section(MY_PORT);
strcpy(response, "ACK");
printf("Printing %s to port %d. \n", response, NEXT_CLIENT_PORT);
int check = sendto(sockfd, (const char*)response, strlen(response), MSG_CONFIRM, (const
struct sockaddr*)&next_client_addr, sizeof(next_client_addr));
memset(&prev_client_addr, 0, sizeof(prev_client_addr));
n = recvfrom(sockfd, (char*)buffer, MAXLINE, MSG_WAITALL, (struct
sockaddr*)&prev_client_addr, &len);
buffer[n] = '\0';
if (!strcmp(buffer, "ACK")) {
strcpy(response, "TERM");
sendto(sockfd, (const char*)response, strlen(response), MSG_CONFIRM, (const struct
sockaddr*)&next_client_addr, sizeof(next_client_addr));
printf("Exiting\n");
} else {
printf("Invalid message recieved\n");
}
exit(0);
} else {
while (1) {
memset(&prev_client_addr, 0, sizeof(prev_client_addr));
printf("Ready to Listen \n");
n = recvfrom(sockfd, (char*)buffer, MAXLINE, MSG_WAITALL, (struct
sockaddr*)&prev_client_addr, &len);
buffer[n] = '\0';
if (!strcmp(buffer, "ACK")) {
critical_section(MY_PORT);
printf("Printing %s to port %d. \n", buffer, NEXT_CLIENT_PORT);
sendto(sockfd, (const char*)buffer, strlen(buffer), MSG_CONFIRM, (const struct
sockaddr*)&next_client_addr, sizeof(next_client_addr));
} else if (!strcmp(buffer, "TERM")) {
printf("Printing %s to port %d. \n", buffer, NEXT_CLIENT_PORT);
sendto(sockfd, (const char*)buffer, strlen(buffer), MSG_CONFIRM, (const struct
sockaddr*)&next_client_addr, sizeof(next_client_addr));
printf("Exiting\n");
exit(0);
} else {
printf("Invalid message recieved\n");
}
}
}
}
PROGRAM OUTPUT:
Findings and Learnings:
1. We successfully implemented Token-Ring Mutual Exclusion.
2. This avoids Starvation
3. Lost Key is a major issue