. UNIX, , . exec , , , , , , "../../../mybin/exe/myprogram". PATH .
: , , , ?
. getcwd(), , , . , .
, , !
a call from main is required using argv [0], I use popen () calls to the shell to make the code suitable in small, popen () is not always an excellent choice, this can be unsuccessful if there are other executables earlier in PATH so same name:
char *
mypath(const char *src)
{
FILE *cmd=NULL;
static char path_2_me[PATH_MAX]={0x0};
char tmp[PATH_MAX]={0x0};
const char *basename=strrchr(src, '/');
if(basename==NULL)
basename=src;
else
basename++;
if(memcmp(src, "./", 2)==0)
sprintf(path_2_me,"%s/%s", getcwd(tmp, PATH_MAX), basename);
else
{
sprintf(tmp, "/usr/bin/which %s", basename);
cmd=popen(tmp, "r");
fgets(path_2_me, sizeof(path_2_me), cmd);
pclose(cmd);
if(memcmp(path_2_me, "no ", 3)==0)
*path_2_me=0x0;
}
return (*path_2_me) ?path_2_me: NULL;
}
source
share