I'm looking for alternative ways to obtain the command line parameters argc
and argv
provided to a process without having direct access to the variables passed into main()
.
I want to make a class that is independent of main()
so that argc
and argv
don't have to be passed explicitly to the code that uses them.
EDIT: Some clarification seems to be in order. I have this class.
class Application
{
int const argc_;
char const** const argv_;
public:
explicit Application(int, char const*[]);
};
Application::Application(int const argc, char const* argv[]) :
argc_(argc),
argv_(argv)
{
}
But I'd like a default constructor Application::Application()
, with some (most probably) C code, that pulls argc
and argv
from somewhere.
On Linux, you can get this information from the process's proc file system, namely /proc/$$/cmdline
:
int pid = getpid();
char fname[PATH_MAX];
char cmdline[ARG_MAX];
snprintf(fname, sizeof fname, "/proc/%d/cmdline", pid);
FILE *fp = fopen(fname);
fgets(cmdline, sizeof cmdline, fp);
// the arguments are in cmdline