I am trying to run a C++ app (under Linux) from another directory. The app is supposed to read some files in the directory where it is. Let's assume the executable is in
/opt/app/proj/
All files to read by the app are in the same directory if I run the code from this directory, everything runs fine. but if I am in /home/user/Document/ and execute the code
/opt/app/proj/application
it does not find the files!! in my C++ code I have added something like:
string cwd(get_current_dir_name());
string path(argv[0]);
string CONFIG_FILE = "configuration.conf";
string FILETYPES = "extensions.txt";
int pos = path.find("./");
if(pos>=0){
path = cwd+path.substr(pos+1, path.length()-1);
}
pos = path.find_last_of("/");
path = path.substr(0,pos+1);
CONFIG_FILE = path + CONFIG_FILE;
FILETYPES = path + FILETYPES;
It still doesn't work.. Need help...
Starting a new process on Linux is, roughly, a two step process:
The fork()
system call.
The child process executes the exec()
system call.
To start the new process from a different directory, just have the child process chdir()
to the directory, before executing the exec()
system call.
If you are using system()
, you can replace it with fork()
+ exec()
, to do this, or since system()
executes the shell, to actually run the command, you can manually prepend the "chdir" command, although this is less clean.
如果您需要查找可执行文件的路径,只需阅读/proc/self/exe
符号链接,则可以在该目录上使用dirname()
或basename()
获取目录,然后将chdir()
移至该位置并访问您的就像您从那里开始一样。
To directly answer your questions, the working directory for Linux is the directory where the executable was started not where is resides. As others mentioned, you can use readlink to get the path from the /proc/self/exe. You can then use the fully qualified path to find other files of interest. Here are some details and examples.
In general, I would not recommend this approach. The two approaches that I've commonly used are:
Thanks very much for your input. Actually my code worked, it just that I was trying to read from the config file before doing this process above. My mistake. Though, I tried to have a look at your propositions to know better about C programming. Thanks again!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.