Reputation: 19331
This could potentially be an xy problem, so I'm open to suggestions that deviate from the original question if there's a better way to approach this.
I have a fairly large program that generates a lot of metrics, statistics, etc. One important calculation that I need is the ability to generate the output of a complex mathematical operation. The only tool that can generate this output is a third-party, vendor-supplied application. The vendor will gladly compile the application for my company for any OS/distory/architecture, but they cannot give us the source. As a result, our program must rely on the pre-compiled program being shipped as part of the same project, and the vendor program being launched via popen()
.
Due to installation mishaps and other issues, there are times that the popen()
call fails due to path issues, the file being moved, etc. These aren't things we can control, but nevertheless, the customer blames it on the devs.
Is there some way, using a simple c plus make on linux program, to somehow embed the external application into our own application so that it can be popen()
'ed in a private memory mapping, so that the program is always available to our "main" application?
Ideally, we would just add the source for this program to our own code base and problem solved, but that's not available to us.
Upvotes: 3
Views: 401
Reputation: 65046
If you really must ship your application as a single binary without auxillary files1, you can just link the entire binary into your application using the linker. The specific details for Linux/ELF/ld
are fleshed out in this answer.
Then, at runtime, just write your binary to a temporary file, then chmod(2)
the permissions programatically to include execute, and finally popen
it as you have been doing.
1 Since if that's not a requirement, the vendor supplied application can just be treated as any other auxillary file which must be present. I don't see how the customer can mess up the executable more than other file in your application directory.
Upvotes: 3
Reputation: 176
This is an interesting question indeed. What I would do would be to include the executable inside your program. The easiest way is to create an array of chars that is a copy of the contents of the executable. At runtime, you then use mkstemp
to create a temporary file and write the content of your char array in it. You then add the execution permissions with chmod
and run with popen
just like you did earlier.
I found this SO question that provides an example of code to do just what I'm describing: How to compile and execute from memory directly?
Upvotes: 1