How to write a C/C++ wrapper program in Linux that

2020-05-09 18:44发布

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

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.

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?

标签: c linux
1条回答
三岁会撩人
2楼-- · 2020-05-09 19:18

Let's say you have the following original program:

foo.sh

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

Make it executable:

$ chmod +x foo.sh

Now the wrapper in 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; 
    }   
}

Run it:

$ gcc wrapper.c
$ ./a.out --foo -b "ar"
Executing wrapper code
Executing original program
Called with: --foo -b ar
$ echo $?
23
查看更多
登录 后发表回答