Get the file that is calling the current executable through a symbolic link

50 Views Asked by At

In a Linux system, I'm trying to write a C program source.c which can behave differently according to the caller through a symbolic link. It compiles into an executable file source, and there are multiple files linked to it:

ln -s source link1

ln -s source link2

I want to make source output differently when I call link1 vs link2, but I can't find a way to recognize, in source.c, the filename of the caller.

I've read the readlink solution, but it only returns the source.

1

There are 1 best solutions below

0
dbush On BEST ANSWER

By convention, argv[0] will contain the name used to invoke the program. You can use this to see which symlink it was called with.

int main(int argc, char *argv[])
{
   if (!strcmp(argv[0], "link1") {
       // do actions for link1
   } else if (!strcmp(argv[0], "link2") {
       // do actions for link2
   } else {
       printf("invoked as unknown name: %s\n", argv[0]);
   }
   return 0;
}