如何在 Linux 中编写完全透明的 C/C++ 包装程序

  • 本文关键字:透明 C++ 程序 包装 Linux c linux
  • 更新时间 :
  • 英文 :


注意:这不是一个要求程序的问题,它询问了一些技术细节,请先看下面的问题。

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

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

假设您有以下原始程序:

foo.sh

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

使其可执行:

$ chmod +x foo.sh

现在包装器C

包装器.c

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

int main(int argc, char* argv[]) {
    printf("Executing wrapper coden");
    /* do something ... */
    printf("Executing original programn");
    if(execv("./foo.sh", argv) == -1) {
        printf("Failed to execute original program: %sn", 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

最新更新