
我有一個二進制守護進程,它在運行時依賴另一個二進制守護程序的存在;我不喜歡這個安排。 (我的程式碼可以在 OS X 和 Linux 上運行,我說 linux 是因為我相信只假設elf
檔案格式是可以的)
我知道xxd
但幸運的是也發現了這篇文章:如何將二進位檔案轉儲為 C/C++ 字串文字?它使用objdump
.
我認為應該可以創建特定於 arch 的 obj 文件,然後在運行時進行如下匹配:
在偽 OCaml 中
match arch with
| Linux_32_bit ->
write_to_file "/tmp/foo" "linux_bin_32";
Child_process.popen "/tmp/foo"
| Darwin_64_bit ->
...
我認為這從表面上看應該可行,假設嵌入二進位檔案的庫存在於正確的位置,以及其他實作細節。
這是否可能或浪費時間?
答案1
你的方法完全沒問題。
下面是一個嵌入 的 C 範例cat
,並在執行時將其寫入臨時文件,並將其標記為可執行:
//$ xxd --include /bin/cat
//^ create _bin_cat and _bin_cat_len
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
int main(){
//TODO: error checking everywhere
char tmp[] = "/tmp/cat-XXXXXX";
mkstemp(tmp);
FILE* f = fopen(tmp, "w");
fwrite(_bin_cat, _bin_cat_len, 1, f);
fchmod(fileno(f), 0700);
puts(tmp); //print the name of where the embeded cat got copied to
return 0;
}
對我來說效果很好。