From a299c8cbcdc4cc541d7b6671bf3784e9de1562a1 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Tue, 23 Aug 2022 22:45:41 +0200 Subject: cmd: add cmd_from_argv --- src/cmd.c | 36 ++++++++++++++++++++++++++++++++++++ src/cmd.h | 2 ++ 2 files changed, 38 insertions(+) (limited to 'src') diff --git a/src/cmd.c b/src/cmd.c index c3ddf6c..f84cb32 100644 --- a/src/cmd.c +++ b/src/cmd.c @@ -5,6 +5,42 @@ #include #include +int cmd_from_argv(struct cmd *cmd, const char *argv[]) +{ + int argc = 0; + + for (const char **s = argv; *s; ++s) + ++argc; + + cmd->argc = argc; + cmd->argv = calloc(argc, sizeof(char *)); + + if (!cmd->argv) { + print_errno("calloc"); + return -1; + } + + for (int i = 0; i < argc; ++i) { + cmd->argv[i] = strdup(argv[i]); + if (!cmd->argv[i]) { + print_errno("strdup"); + goto free; + } + } + + return 0; + +free: + for (int i = 0; i < argc; ++i) + if (cmd->argv[i]) + free(cmd->argv[i]); + else + break; + + free(cmd->argv); + return -1; +} + static size_t calc_buf_len(int argc, char **argv) { size_t len = 0; diff --git a/src/cmd.h b/src/cmd.h index f9b3c6b..9f519f6 100644 --- a/src/cmd.h +++ b/src/cmd.h @@ -6,6 +6,8 @@ struct cmd { char **argv; }; +int cmd_from_argv(struct cmd *, const char *argv[]); + int cmd_send(int fd, const struct cmd *); int cmd_send_and_wait_for_result(int fd, const struct cmd *, int *result); -- cgit v1.2.3