stephane/libmodbus — Issue #47: Need to clone modbus_t TCP context
Author: fspreen-logikos
Created: 2012-02-08 19:27:41+00:00
State: open

In order to create a multi-threaded TCP server, it is necessary to duplicate the modbus_t TCP context, but no function currently exists to do this. Additionally, the modbus_t structure points to connection-specific data, so a simple memcpy() doesn't do the job.

Below is a patch which provides the appropriate functions.

diff -r a/libmodbus/src/modbus-tcp.c b/libmodbus/src/modbus-tcp.c
--- a/libmodbus/src/modbus-tcp.c
+++ b/libmodbus/src/modbus-tcp.c
@@ -732,3 +732,19 @@

return ctx;
}
+
+void modbus_clone_tcp(modbus_t* new_ctx, modbus_t* ctx)
+{
+ new_ctx = (modbus_t *) malloc(sizeof(modbus_t));
+ memcpy(new_ctx, ctx, sizeof(modbus_t));
+ new_ctx->backend_data = (modbus_tcp_t *) malloc(sizeof(modbus_tcp_t));
+ memcpy(new_ctx->backend_data, ctx->backend_data, sizeof(modbus_tcp_t));
+}
+
+void modbus_clone_tcp_pi(modbus_t* new_ctx, modbus_t* ctx)
+{
+ new_ctx = (modbus_t *) malloc(sizeof(modbus_t));
+ memcpy(new_ctx, ctx, sizeof(modbus_t));
+ new_ctx->backend_data = (modbus_tcp_pi_t *) malloc(sizeof(modbus_tcp_pi_t));
+ memcpy(new_ctx->backend_data, ctx->backend_data, sizeof(modbus_tcp_pi_t));
+}
diff -r a/libmodbus/src/modbus-tcp.h b/libmodbus/src/modbus-tcp.h
--- a/libmodbus/src/modbus-tcp.h
+++ b/libmodbus/src/modbus-tcp.h
@@ -41,9 +41,11 @@
modbus_t* modbus_new_tcp(const char *ip_address, int port);
int modbus_tcp_listen(modbus_t *ctx, int nb_connection);
int modbus_tcp_accept(modbus_t *ctx, int *socket);
+void modbus_clone_tcp(modbus_t *new_ctx, modbus_t *ctx);

modbus_t* modbus_new_tcp_pi(const char *node, const char *service);
int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection);
int modbus_tcp_pi_accept(modbus_t *ctx, int *socket);
+void modbus_clone_tcp_pi(modbus_t *new_ctx, modbus_t *ctx);

#endif /* _MODBUS_TCP_H_ */