Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/queue.h>
- struct node {
- pid_t client_pid;
- long n;
- TAILQ_ENTRY(node) nodes;
- };
- struct request_msg_buf {
- long mtype;
- struct {
- pid_t client_pid;
- long n;
- } info;
- };
- struct response_msg_buf {
- long mtype;
- };
- int main() {
- TAILQ_HEAD(head_s, node) head;
- TAILQ_INIT(&head);
- int msqid;
- char pathname[] = "server.c";
- key_t key;
- long n = 0;
- struct request_msg_buf request;
- struct response_msg_buf response;
- if ((key = ftok(pathname, 0)) < 0) {
- printf("Can't generate key\n");
- exit(-1);
- }
- if ((msqid = msgget(key, 0666 | IPC_CREAT)) < 0) {
- printf("Can't get msqid\n");
- exit(-1);
- }
- while (1) {
- if (msgrcv(msqid, (struct msgbuf*) &request, sizeof(request.info), 1, 0) < 0) {
- printf("Can't receive message\n");
- exit(-1);
- }
- printf("A request for access was received:\n\tProcess PID: %d; N: %ld\n", request.info.client_pid, request.info.n);
- if (request.info.n >= 0) {
- n += request.info.n;
- response.mtype = request.info.client_pid;
- msgsnd(msqid, (struct msgbuf*) &response, 0, 0);
- printf("Process with PID %d freed up %ld resources\n", request.info.client_pid, request.info.n);
- } else {
- struct node* new_node = malloc(sizeof(struct node));
- new_node->client_pid = request.info.client_pid;
- new_node->n = request.info.n;
- TAILQ_INSERT_TAIL(&head, new_node, nodes);
- printf("Process with PID %d is waiting for %ld resources...\n", request.info.client_pid, -request.info.n);
- }
- struct node* first_node = TAILQ_FIRST(&head);
- while (!TAILQ_EMPTY(&head) && -first_node->n <= n) {
- long client_pid = first_node->client_pid;
- long needed_n = -first_node->n;
- n -= needed_n;
- TAILQ_REMOVE(&head, first_node, nodes);
- response.mtype = client_pid;
- msgsnd(msqid, (struct msgbuf*) &response, 0, 0);
- printf("Process with PID %ld is provided with needed resources\n", client_pid);
- }
- printf("Current free resources:%ld\n", n);
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment