Skip to content

Instantly share code, notes, and snippets.

@jchip
Created June 11, 2017 21:19
Show Gist options
  • Select an option

  • Save jchip/89a3776f0764c38e1ccbc3a7cbcf10c3 to your computer and use it in GitHub Desktop.

Select an option

Save jchip/89a3776f0764c38e1ccbc3a7cbcf10c3 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libgen.h>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char **argv)
{
string exe_path;
// Not relative or absolute path
if (NULL == strchr(argv[0], '/'))
{
// search PATH
size_t pos_a = 0, pos_b = 0;
string path(getenv("PATH"));
vector<string> paths;
while (pos_b < path.size())
{
pos_b = path.find(":", pos_a);
if (string::npos == pos_b)
{
pos_b = path.size();
}
if (pos_b > pos_a)
{
string check = path.substr(pos_a, pos_b - pos_a) + "/" + argv[0];
if (0 == access(check.c_str(), X_OK))
{
exe_path = check;
break;
}
}
pos_a = pos_b + 1;
}
}
else
{
char *mp = realpath(argv[0], NULL);
if (mp)
{
exe_path = mp;
}
}
if (exe_path.empty())
{
fprintf(stderr, "Unable to determine realpath of %s\n", argv[0]);
exit(-1);
}
char *my_dir = dirname((char *)exe_path.c_str());
string node_path(my_dir);
size_t dir_len = node_path.find_last_of("/");
string top_dir(
node_path, 0,
string::npos == dir_len
? node_path.size()
: dir_len);
free(my_dir);
node_path += "/_node";
char *args[argc + 3];
int copy_off = 0;
string flat_module = top_dir + "/lib/node_modules/flat-module";
if (0 == access(flat_module.c_str(), F_OK))
{
printf("node_path %s flat_module %s\n", node_path.c_str(), flat_module.c_str());
copy_off = 2;
args[1] = (char *)"-r";
args[2] = (char *)flat_module.c_str();
}
printf("argc %d\n", argc);
for (int i = 1; i < argc; i++)
{
args[i + copy_off] = argv[i];
}
args[0] = (char *)exe_path.c_str();
args[argc + copy_off] = NULL;
execv(node_path.c_str(), args);
fprintf(stderr, "Executing %s failed\n", node_path.c_str());
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment