SK/processes/c2-cipc.c

73 lines
1.6 KiB
C
Raw Normal View History

2023-02-10 17:00:31 +01:00
#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 <string.h>
#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)
handle_error("file access");
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)) == -1)
handle_error("msgget");
pid_t pid = getpid();
key_t pid_key;
if ((pid_key = ftok(main_key_file, pid)) == -1)
handle_error("ftok data");
int d_msg_id;
if ((d_msg_id = msgget(pid_key, 0600 | IPC_CREAT)) == -1)
handle_error("msgget pid");
msg_pid pid_msg;
pid_msg.mtype = 1;
pid_msg.pid = getpid();
if (msgsnd(m_msg_id, (void *)&pid_msg, sizeof(pid_t), 0) == -1)
handle_error("msgsnd pid");
msg_data data_msg;
data_msg.mtype = 1;
data_msg.data = 22.211;
if (msgsnd(d_msg_id, (void *)&data_msg, sizeof(double), 0) == -1)
handle_error("msgsnd data");
if (msgrcv(d_msg_id, (void *)&data_msg, sizeof(double), 2, 0600) == -1)
handle_error("msgrcv data");
printf("%f\n", data_msg.data);
if (msgctl(d_msg_id, IPC_RMID, NULL) == -1)
handle_error("msgctl RMID");
return 0;
}