#ifndef__CLIENT_H_#define__CLIENT_H_#include<stdio.h>#include<modbus.h>#include<stdlib.h>#include<string.h>#include<pthread.h>#include<unistd.h>#include<sys/ipc.h>#include<sys/shm.h>#include<errno.h>#include<sys/types.h>#include<sys/msg.h>#defineSHM_SIZE64structshm{
uint16_t buf[4];// int flag;};structmsgbuf{
long mtype;/* message type, must be > 0 */uint8_t ctl[2];/* message data */};intinit_modbus(modbus_t**,constchar*,int);structshm*init_shared_memory(key_t*,int*);intinit_msg_queue(key_t*,int*);#endif
func.c
#include"client.h"intinit_modbus(modbus_t**ctx,constchar*ip,int port){
*ctx =modbus_new_tcp(ip, port);if(*ctx ==NULL){
perror("Failed to modbus_new_tcp");return-1;}if(modbus_set_slave(*ctx,1)<0){
perror("Failed to modbus_set_slave");return-2;}if(modbus_connect(*ctx)<0){
perror("Failed to modbus_connect");return-3;}return0;}structshm*init_shared_memory(key_t*key,int*shmid){
*key =ftok("./client.c",'v');// ftok(任意文件名/路径名, 任意字符);if(key <0){
perror("Failed to ftok");returnNULL;}*shmid =shmget(*key, SHM_SIZE, IPC_CREAT | IPC_EXCL |0666);if(*shmid <0){
if(errno == EEXIST)*shmid =shmget(*key, SHM_SIZE,0666);else{
perror("Failed to shmget");returnNULL;}}structshm*p =shmat(*shmid,NULL,0);// 0 表示可读可写, 若只读则 SHM_RDONLYif(p ==(void*)-1){
// if (*p == -1) 也可以perror("Failed to shmat");returnNULL;}return p;}intinit_msg_queue(key_t*key,int*msgid){
*key =ftok("./client.h",'v');if(*key <0){
perror("Failed to ftok");return-4;}*msgid =msgget(*key, IPC_CREAT | IPC_EXCL |0666);if(