【问题标题】:How to pass multiple values from C program to shell script如何将多个值从 C 程序传递到 shell 脚本
【发布时间】:2020-12-12 08:52:10
【问题描述】:

我有一个 shell 脚本,它执行一些基本功能,并为每个操作使用特定的命令行参数调用 c 程序。

C程序返回整数值,表示成功或失败。

现在我有一种情况,c 程序需要几个值,并且需要由父脚本访问。有什么办法可以实现吗? [除了将值存储在临时文件中以及访问文件以获取值的脚本]

【问题讨论】:

  • 如果逻辑允许,可能是一个管道
  • 考虑使用示例输入和输出,以便 SO 读者了解您要解决的问题

标签: c shell process environment-variables


【解决方案1】:

让您的 C 程序将值写入其stdout,并使用 命令替换 shell 功能在父脚本中捕获这些值,类似于

program_output=$(your_c_program with the arguments it needs)

man bash(并搜索命令替换)了解详情。

【讨论】:

    【解决方案2】:

    您可以使用excecl 命令

    int execl(const char *path, const char *arg, ...);
    

    像这样:

    #include <stdio.h>
    #include <unistd.h>
    #include <dirent.h>
    
    void main () {
    
       return execl ("/bin/pwd", "pwd", NULL);
    
    }
    

    【讨论】:

    • 可能是我的问题有点混乱。让我举个例子。假设我有一个脚本 test1.sh,我从中调用了一个可执行的 exe1。这个 exe1(c 程序)会得到一些值,比如 val1 和 val2。这些值应该返回到脚本 test1.sh,以便我可以继续对 val1 和 val2 进行其他操作。
    【解决方案3】:

    是的,看看 exec 系统调用,有多个函数可以帮助你实现这一点,但基本上你可以执行一个 c 程序并将你想要/需要的所有参数传递给它

    https://linuxhint.com/exec_linux_system_call_c/

    【讨论】:

    • 基本上shell脚本是调用C程序的父级。反之亦然。
    • 假设您的可执行文件名为 main,并且您希望将以下参数传递给它:arg1、arg2 和 arg3。你可以通过在 shell 中输入:./main arg1 arg2 arg3
    猜你喜欢
    • 2021-09-20
    • 1970-01-01
    • 2013-08-22
    • 2018-01-06
    • 1970-01-01
    • 2013-11-10
    • 2013-05-07
    • 1970-01-01
    • 2013-08-13
    相关资源
    最近更新 更多