SK/processes/c-sipc.c
Dawid Pietrykowski d5a3f7150c IPC
2023-01-28 13:34:00 +01:00

122 lines
3.0 KiB
C

#include <unistd.h>
#include <stdio.h>
#include <sys/uio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
const char *main_path = "/tmp/serweripcmain";
typedef struct DanePid
{
long mtype; /* Message type. */
pid_t pid; /* Message text. */
} dane_pid;
typedef struct DaneDouble
{
long mtype; /* Message type. */
double n; /* Message text. */
} dane_double;
int f;
int msg_id;
void end()
{
close(f);
msgctl(msg_id, IPC_RMID, NULL);
exit(0);
}
int main(int argc, char *argv[])
{
signal(SIGTERM, end);
signal(SIGINT, end);
key_t key;
if ((f = open(main_path, O_CREAT | O_RDWR, 0600)) == -1)
{
perror("open main file error");
return -1;
}
else
{
close(f);
}
if ((key = ftok(main_path, 1)) == -1)
{
perror("main ftok error");
return -1;
}
if ((msg_id = msgget(key, 0600 | IPC_CREAT)) == -1)
{
perror("msgget error");
return -1;
}
printf("Created queue with id %d\n", msg_id);
dane_pid pid_dane;
dane_double dane_double;
ssize_t bytes;
for (;;)
{
if ((bytes = msgrcv(msg_id, (void *)&pid_dane, sizeof(pid_t), 1, 0)) == -1)
{
perror("msgrcv error");
msgctl(msg_id, IPC_RMID, NULL);
return -1;
}
printf("Received %d bytes\n", bytes);
printf("Dane: %d\n", pid_dane.pid);
pid_t pid;
if ((pid = fork()) == -1)
{
msgctl(msg_id, IPC_RMID, NULL);
return -1;
}
if (pid == 0)
{
key_t key;
int f;
if ((key = ftok(main_path, pid_dane.pid)) == -1)
{
perror("child ftok error");
return -1;
}
int child_msg_id;
if ((child_msg_id = msgget(key, 0600 | IPC_CREAT)) == -1)
{
perror("child msgget error");
return -1;
}
printf("Created queue with id %d\n", child_msg_id);
if ((bytes = msgrcv(child_msg_id, (void *)&dane_double, sizeof(double), 2, 0)) == -1)
{
perror("msgrcv error");
msgctl(msg_id, IPC_RMID, NULL);
return -1;
}
printf("Child received %d bytes and value %f\n", bytes, dane_double.n);
dane_double.n = dane_double.n * dane_double.n;
dane_double.mtype = 3;
if (msgsnd(child_msg_id, (const void *)&dane_double, sizeof(double), 0) == -1)
{
perror("data send error");
return -1;
}
printf("Sent %d bytes data: %f\n", sizeof(double), dane_double.n);
if (msgctl(child_msg_id, IPC_RMID, NULL) == -1)
{
perror("child msgctl IPC_RMID error");
return -1;
}
}
}
if (msgctl(msg_id, IPC_RMID, NULL) == -1)
{
perror("msgctl IPC_RMID error");
return -1;
}
}