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 <unistd.h>
- #include <time.h>
- struct request_msg_buf {
- long mtype;
- struct {
- pid_t client_pid;
- long n;
- } info;
- };
- struct response_msg_buf {
- long mtype;
- };
- int main() {
- srand(time(NULL));
- int msqid; // IPC-дескриптор очереди сообщений
- char pathname[] = "server.c";
- key_t key; // IPC-ключ
- 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);
- }
- request.mtype = 1;
- request.info.client_pid = getpid();
- request.info.n = (rand() % 11) - 5;
- if (msgsnd(msqid, (struct msgbuf*) &request, sizeof(request.info), 0) < 0) {
- printf("Can't send message to queue\n");
- msgctl(msqid, IPC_RMID, (struct msqid_ds*) NULL);
- exit(-1);
- }
- if (request.info.n >= 0)
- printf("Freeing up %ld resources\n", request.info.n);
- else
- printf("Waiting for %ld resources\n", -request.info.n);
- msgrcv(msqid, (struct msgbuf*) &response, 0, request.info.client_pid, 0);
- printf("All right, process is terminated.\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment