Reputation: 891
I am working on a project in which I need to know the current working directory of the executable which called the system call. I think it would be possible as some system calls like open
would make use of that information.
Could you please tell how I can get the current working directory path in a string?
Upvotes: 6
Views: 4751
Reputation: 596
In newer kernels things changed a little bit. You can use this to get the current working directory:
#include <linux/init.h> // module_{init,exit}()
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/dcache.h> // dentry_path_raw
#include <linux/fs_struct.h> // get_fs_pwd
static int __init get_cwd_module_init(void)
{
struct path abs_path;
char *buf, *full_path;
buf = __getname();
if (!buf)
return -ENOMEM;
get_fs_pwd(current->fs, &abs_path);
full_path = dentry_path_raw(abs_path.dentry, buf, PATH_MAX);
if (IS_ERR(full_path)) {
pr_err("dentry_path_raw failed: %li", PTR_ERR(full_path));
} else {
pr_info("Full path: '%s'", full_path);
}
__putname(buf);
path_put(&abs_path);
}
static void __exit get_cwd_module_exit(void)
{
pr_info("exiting...");
}
module_init(get_cwd_module_init)
module_exit(get_cwd_module_exit)
MODULE_AUTHOR("garlix");
MODULE_LICENSE("GPL");
Upvotes: 0
Reputation: 5030
How do you do that in a terminal ? You use pwd
which looks at the environment variable named PWD
.
#include <stdlib.h>
int main(int ac, char **av) {
printf("%s\n", getenv("PWD");
return 0;
}
If you want to know in which directory the executable is located you can combine the information from getenv
and from argv[0]
.
Upvotes: -1
Reputation: 206727
You can look at how the getcwd
syscall is implemented to see how to do that.
That syscall is in fs/dcache.c
and calls:
get_fs_root_and_pwd(current->fs, &root, &pwd);
root
and pwd
are struct path
variables,
That function is defined as an inline function in include/linux/fs_struct.h
, which also contains:
static inline void get_fs_pwd(struct fs_struct *fs, struct path *pwd)
and that seems to be what you are after.
Upvotes: 12