0

I have a piece of C++ code that calls the system command.. I want to pass the file name of my own C++ executable to the system command.. anyone know how to do this? So for example my C++ code is called "switch-5".. what I want to do is something like;

system("./script.sh switch-5");

Anyone have any clue?

Alex van Es
  • 1,141
  • 2
  • 15
  • 27

4 Answers4

6

Your executable name is the first argument passed in argv.

To test this just run:

int main(int argc, char **argv)
{
   printf("My program name: '%s'\n", argv[0]);
   return 0;
}

(I am assuming you know how to combine it with your script name to get the string to pass to system().)

Nathan S.
  • 5,244
  • 3
  • 45
  • 55
  • 1
    If you have put the executable on your path and are therefore able to call it without a real path specifier, then only the base name that you used to call it will be in argv[0]. So if you want to do stuff like find a file relative to the executable you'll have to find a different way. – Simon Jul 14 '12 at 07:15
0

argv[0] as passed to main is the name of your executable.

JimR
  • 15,513
  • 2
  • 20
  • 26
  • While `argv[0]` tends to be the name of executable, my understanding is that it's a convention and not guaranteed... – reuben Jul 14 '12 at 05:34
  • @rueben: You may be right. But I believe when it is not, it's because the program modified it. IIRC some of the programs in SAMBA do this to avoid leaking passwords in /proc and the output from ps. – JimR Jul 14 '12 at 05:40
  • There's more background here on the full story: http://stackoverflow.com/questions/383973/is-args0-guaranteed-to-be-the-path-of-execution – reuben Jul 14 '12 at 05:42
0

Store it in a global variable during app startup:

static char *selfname;

int main(int argc, char **argv)
{
    selfname = argv[0];

    // etc.
}
0

Beware, argv[0] contains exactly what was used to start the program, including relative or absolute path, for example: "./programname".