static struct iio_context * get_context(int fd) { struct iio_context *ctx; char *xml; long xml_len = exec_command("PRINT\r\n", fd); if (xml_len < 0) { errno = (int) -xml_len; return NULL; } DEBUG("Server returned a XML string of length %li\n", xml_len); xml = malloc(xml_len); if (!xml) { errno = ENOMEM; return NULL; } DEBUG("Reading XML string...\n"); read_all(xml, xml_len, fd); DEBUG("Creating context from XML...\n"); ctx = iio_create_xml_context_mem(xml, xml_len); if (ctx) ctx->xml = xml; else free(xml); return ctx; }
struct iio_context * iiod_client_create_context( struct iiod_client *client, int desc) { struct iio_context *ctx = NULL; size_t xml_len; char *xml; int ret; iio_mutex_lock(client->lock); ret = iiod_client_exec_command(client, desc, "PRINT\r\n"); if (ret < 0) goto out_unlock; xml_len = (size_t) ret; xml = malloc(xml_len + 1); if (!xml) { ret = -ENOMEM; goto out_unlock; } /* +1: Also read the trailing \n */ ret = (int) iiod_client_read_all(client, desc, xml, xml_len + 1); if (ret < 0) goto out_free_xml; ctx = iio_create_xml_context_mem(xml, xml_len); if (!ctx) ret = -errno; out_free_xml: free(xml); out_unlock: iio_mutex_unlock(client->lock); if (!ctx) errno = -ret; return ctx; }
int main(int argc, char **argv) { char *xml; struct iio_context *ctx; int c, option_index = 0, arg_index = 0, xml_index = 0, ip_index = 0; enum backend backend = LOCAL; while ((c = getopt_long(argc, argv, "+hn:x:", options, &option_index)) != -1) { switch (c) { case 'h': usage(); return EXIT_SUCCESS; case 'n': if (backend != LOCAL) { fprintf(stderr, "-x and -n are mutually exclusive\n"); return EXIT_FAILURE; } backend = NETWORK; arg_index += 2; ip_index = arg_index; break; case 'x': if (backend != LOCAL) { fprintf(stderr, "-x and -n are mutually exclusive\n"); return EXIT_FAILURE; } backend = XML; arg_index += 2; xml_index = arg_index; break; case '?': return EXIT_FAILURE; } } if (arg_index >= argc) { fprintf(stderr, "Incorrect number of arguments.\n\n"); usage(); return EXIT_FAILURE; } if (backend == XML) ctx = iio_create_xml_context(argv[xml_index]); else if (backend == NETWORK) ctx = iio_create_network_context(argv[ip_index]); else ctx = iio_create_default_context(); if (!ctx) { fprintf(stderr, "Unable to create IIO context\n"); return EXIT_FAILURE; } xml = strdup(iio_context_get_xml(ctx)); if (!xml) { iio_context_destroy(ctx); return EXIT_FAILURE; } printf("XML generated:\n\n%s\n\n", xml); iio_context_destroy(ctx); ctx = iio_create_xml_context_mem(xml, strlen(xml)); if (!ctx) { fprintf(stderr, "Unable to re-generate context\n"); } else { printf("Context re-creation from generated XML suceeded!\n"); iio_context_destroy(ctx); } free(xml); return EXIT_SUCCESS; }