Alternative way to obtain argc and argv of a process Alternative way to obtain argc and argv of a process windows windows

Alternative way to obtain argc and argv of a process


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


The arguments to main are defined by the C runtime, and the only standard/portable way to obtain the command line arguments. Don't fight the system. :)

If all you want to do is to provide access to command line parameters in other parts of the program with your own API, there are many ways to do so. Just initialise your custom class using argv/argc in main and from that point onward you can ignore them and use your own API. The singleton pattern is great for this sort of thing.

To illustrate, one of the most popular C++ frameworks, Qt uses this mechanism:

int main(int argc, char* argv[]){    QCoreApplication app(argc, argv);    std::cout << app.arguments().at(0) << std::endl;    return app.exec();}

The arguments are captured by the app and copied into a QStringList. See QCoreApplication::arguments() for more details.

Similarly, Cocoa on the Mac has a special function which captures the command line arguments and makes them available to the framework:

#import <Cocoa/Cocoa.h>int main(int argc, char *argv[]){    return NSApplicationMain(argc, (const char **)argv);}

The arguments are then available anywhere in the app using the NSProcessInfo.arguments property.

I notice in your updated question that your class directly stores a copy of argc/argv verbatim in its instance:

int const argc_;char const** const argv_;

While this should be safe (the lifetime of the argv pointers should be valid for the full lifetime of the process), it is not very C++-like. Consider creating a vector of strings (std::vector<std::string>) as a container and copy the strings in. Then they can even be safely mutable (if you want!).

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.

It is not clear why passing this info from main is somehow a bad thing that is to be avoided. This is just how the major frameworks do it.

I suggest you look at using a singleton to ensure there is only one instance of your Application class. The arguments can be passed in via main but no other code need know or care that this is where they came from.

And if you really want to hide the fact that main's arguments are being passed to your Application constructor, you can hide them with a macro.


To answer the question in part, concerning Windows, the command line can be obtained as the return of the GetCommandLine function, which is documented here, without explicit access to the arguments of the main function.