SK/processes/ipc/c2-sipc.c
Dawid Pietrykowski 5c3cc72f24 reorganization
2023-02-11 11:19:32 +01:00

80 lines
1.9 KiB
C

#include <unistd.h>
#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h> /* Definition of SYS_* constants */
#include <sys/msg.h>
const char *main_key_file = "/tmp/IPC-SERVER-43412321";
struct Msg_pid
{
long mtype;
pid_t pid;
} typedef msg_pid;
struct Msg_data
{
long mtype;
double data;
} typedef msg_data;
void handle_error(char *txt)
{
perror(txt);
exit(-1);
}
int main()
{
if (access(main_key_file, F_OK) == 0)
unlink(main_key_file);
if (mknod(main_key_file, 0600 | S_IFREG, NULL) != 0)
handle_error("main file creation");
key_t main_key;
if ((main_key = ftok(main_key_file, 0)) == -1)
handle_error("ftok");
int m_msg_id;
if ((m_msg_id = msgget(main_key, 0600 | IPC_CREAT)) == -1)
handle_error("msgget");
msg_pid pid_msg;
while (1)
{
if (msgrcv(m_msg_id, (void *)&pid_msg, sizeof(pid_t), 1, 0) == -1)
handle_error("msgrcv");
printf("%d\n", pid_msg.pid);
int pid;
if ((pid = fork()) == -1)
handle_error("fork");
if (pid == 0)
{
key_t pid_key;
if ((pid_key = ftok(main_key_file, pid_msg.pid)) == -1)
handle_error("ftok data");
int d_msg_id;
if ((d_msg_id = msgget(pid_key, 0600)) == -1)
handle_error("msgget data");
msg_data data_msg;
if (msgrcv(d_msg_id, (void *)&data_msg, sizeof(double), 1, 0600) == -1)
handle_error("msgrcv data");
printf("Received data %f\n", data_msg.data);
data_msg.mtype = 2;
data_msg.data *= data_msg.data;
if (msgsnd(d_msg_id, (void *)&data_msg, sizeof(double), 0) == -1)
handle_error("msgsnd data");
}
}
if (msgctl(m_msg_id, IPC_RMID, NULL) == -1)
handle_error("msgctl RMID");
return 0;
}