Getting Current Working Directory Within Kernel Code

Getting current working directory within kernel code

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.

current directory of a process in linux-kernel

Your working on quite an old kernel so I've had to do some digging. One of the easier ways to deal with this sort of thing is see if the information is in /proc and look at what it does. If we grep for cwd in fs/proc we find:

static int proc_cwd_link(struct inode *inode, struct dentry   **dentry,   struct vfsmount **mnt)
{
struct fs_struct *fs;
int result = -ENOENT;
task_lock(inode->u.proc_i.task);
fs = inode->u.proc_i.task->fs;
if(fs)
atomic_inc(&fs->count);
task_unlock(inode->u.proc_i.task);
if (fs) {
read_lock(&fs->lock);
*mnt = mntget(fs->pwdmnt);
*dentry = dget(fs->pwd);
read_unlock(&fs->lock);
result = 0;
put_fs_struct(fs);
}
return result;
}

The proc inode points to the task (inode->u.proc_i.task, also given away by the task_lock() stuff). Looking at the task_struct definition it has a reference to struct fs_struct *fs which has the dentry pointers for the pwd. Translating the dentry entry to an actual name is another exercise however.

How/where is the working directory of a program stored?

Current directory is maintained by the OS, not by language or framework. See description of GetCurrentDirectory WinAPI function for details.

From description:

Multithreaded applications and shared
library code should not use the
GetCurrentDirectory function and
should avoid using relative path
names. The current directory state
written by the SetCurrentDirectory
function is stored as a global
variable in each process, therefore
multithreaded applications cannot
reliably use this value without
possible data corruption from other
threads that may also be reading or
setting this value.

How to change working directory in Jupyter Notebook?

Running os.chdir(NEW_PATH) will change the working directory.

import os
os.getcwd()
Out[2]:
'/tmp'
In [3]:

os.chdir('/')
In [4]:

os.getcwd()
Out[4]:
'/'
In [ ]:


Related Topics



Leave a reply



Submit