如何在Linux中编写完全透明的C/C ++包装程序 [英] How to write a C/C++ wrapper program in Linux that is fully transparent

查看:53
本文介绍了如何在Linux中编写完全透明的C/C ++包装程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这不是要求程序的问题,它询问一些技术细节,请首先参见下面的问题.

Note: This is not a question to ask for a program, It asks about some tech details, see the question bellow first.

我需要为现有程序编写C/C ++包装程序.我知道我们需要使用exec/fork/system并传递参数,然后返回程序的结果.

I need to write a wrapper program in C/C++ for an existing program. I know we need to use exec/fork/system and pass through the parameters then return the result of the program.

问题是,如何确保调用程序(调用包装程序)和包装程序都完全像以前一样工作(忽略时序差异).可能需要处理一些细微的事情,例如环境参数. fork/system/exec,该使用哪个?够了吗?还有其他因素要考虑吗?

The question is, how to ensure that both the invoker program(that invoke the wrapper) and the wrapped program work exactly like before (ignore timing differences). There maybe subtle things like environment parameters to deal with. fork/system/exec, which to use? Are they enough? Are there other factors to consider?

推荐答案

假设您有以下原始程序:

Let's say you have the following original program:

foo.sh

#!/bin/bash
echo "Called with: ${@}"
exit 23

使其可执行:

$ chmod +x foo.sh

现在将包装器放入C:

wrapper.c

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>


int main(int argc, char* argv[]) {
    printf("Executing wrapper code\n");

    /* do something ... */

    printf("Executing original program\n");
    if(execv("./foo.sh", argv) == -1) {
        printf("Failed to execute original program: %s\n", strerror(errno));
        return -1; 
    }   
}

运行它:

$ gcc wrapper.c
$ ./a.out --foo -b "ar"
Executing wrapper code
Executing original program
Called with: --foo -b ar
$ echo $?
23

这篇关于如何在Linux中编写完全透明的C/C ++包装程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆