gpt4 book ai didi

c - 如何从 C 函数创建 shell 命令

转载 作者:太空狗 更新时间:2023-10-29 15:31:19 25 4
gpt4 key购买 nike

想知道如何使用一组 C 函数并将它们转换为 shell/bash 命令。

假设我有一组简单的 C 函数

int
fn1() {
// some C code for function 1.
}

int
fn2() {
// some C code for function 2.
}

int
fn3() {
// some C code for function 3.
}

然后我想以某种方式创建 CLI 命令,以便我可以从终端使用它们。

$ fn1 <param> <param> ...
$ fn2 ...
$ fn3 ...

不确定执行此操作的过程。如果我需要以某种方式重写 shell 脚本中的所有函数接口(interface),然后以某种方式调用 C 函数,有点像这样(bash 脚本):

fn1() {
callc mylib/fn1 $1 $2
}

fn2() {
...
}

...

或者如果我可以通过将每个 C 函数分成单独的文件 fn1.cfn2.c 等以某种方式自动将它们转换为 shell 脚本使用 source ~/.bash_profile 类型的东西将它们加载到 shell 中。

如有任何帮助,我们将不胜感激。

最佳答案

或者走老路,也许:编写 C 代码来检查它是如何被调用的(原始命令行参数中的第 0 个参数)并根据该名称调用正确的 C 函数。需要将此类 C 程序编译为单个可执行文件,然后创建指向基本应用程序的符号链接(symbolic link),其中符号链接(symbolic link)是相关函数的名称。除了将此处的工件(可执行文件和符号链接(symbolic link))安装到 $PATH 中的目录中之外,不需要 shell 代码。

例子。如果以下代码的名称为 toybox.c,并且 ~/bin 存在并且在用户的 $PATH 中,请使用如下内容:

$ cc -o ~/bin/toybox toybox.c
$ ln -s toybox ~/bin/fn1
$ ln -s toybox ~/bin/fn2
$ ln -s toybox ~/bin/fn3

简单测试 - 仅显示脚手架就位。

$ fn1
fn1 invoked - no arguments.
$ fn3 1 2 'a b c'
fn3 invoked - arguments:
1 - '1'
2 - '2'
3 - 'a b c'

toybox.c 的源代码可能如下所示:

#include <string.h>
#include <libgen.h>
#include <stdio.h>

struct name2func {
const char *name;
int (*func)(int ac, char *const av[]);
};

void
fn_debug(const char *fn, int ac, char *const av[])
{
int n;

printf("%s invoked - ", fn);

if (ac <= 0) {
printf("no arguments.\n");
} else {
printf("arguments:\n");
for (n = 0; n < ac; n++) {
printf(" %d - '%s'\n", n + 1, av[n]);
}
}
}

int
fn1(int ac, char *const av[])
{
fn_debug("fn1", ac, av);
/* some C code for function 1. */
return 0;
}

int
fn2(int ac, char *const av[])
{
fn_debug("fn2", ac, av);
/* some C code for function 2. */
return 0;
}

int
fn3(int ac, char *const av[])
{
fn_debug("fn3", ac, av);
/* some C code for function 3. */
return 0;
}

/*
* Establish a crude symbol table after function definitions: size of
* the name2func array (i.e., its number of elements) is available via the
* sizeof builtin.
*/

struct name2func n2f[] = {
{ "fn1", fn1 },
{ "fn2", fn2 },
{ "fn3", fn3 }
};

int
dispatch(const char *func_name, int ac, char *const av[])
{
size_t n;

/* linear search ok for small # of funcs */

for (n = 0; n < sizeof n2f / sizeof n2f[0]; n++) {
if (strcmp(func_name, n2f[n].name) == 0) {
return (*n2f[n].func)(ac, av);
}
}

fprintf(stderr, "%s: unsupported\n", func_name);
return 1;
}

int
main(int argc, char *const argv[])
{
/*
* using POSIX basename(3) to create, say, "fn1" from
* a full-path invocation like "/my/odd/dir/fn1".
*/
char *fnbase = basename(argv[0]);

if (fnbase == 0) {
perror("basename");
return 1;
}

return dispatch(fnbase, argc - 1, argv + 1);
}

关于c - 如何从 C 函数创建 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51918893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com