3

I have a program a.out running from /tmp/test. If I list /proc/$(pgrep a.out)/cwd, it is a symbolic link to /tmp/test.

Now, I bind /mnt/othertest onto /tmp/test with mount -o bind /mnt/othertest /tmp/test. Thus, this new mount is stacked and old /tmp/test is hidden.

Still, since a.out was launched before mount command, it has access to the old path.

The problem I want to tackle is how to know if a process with cwd set to /tmp/test refers to the directory from /mnt/othertest or not.

For opened files, it is easy, I can use fdinfo from proc pseudo-filesyste and read the mount id, but I did not find such information for cwd. I could check the start time of the process and compare it with the time when mount was launched, but because of possible forks it could be wrong.

  • Related, if not a dupe: Determine what device a directory is located on – Kusalananda Aug 26 '19 at 20:39
  • Also possibly interesting (unless I'm misunderstanding the question): How to get mount point of filesystem containing given file – Kusalananda Aug 26 '19 at 20:39
  • @Kusalananda It is not related since my directory is hidden by the stack from the new mount. And I want to know if it refers to the old device or not. – rools Aug 26 '19 at 20:43
  • Does a process have the old directory as its current directory? In that case, the current directory refers to the hidden directory. Can't test this as I don't have a Unix with bind mounts available ATM. – Kusalananda Aug 26 '19 at 20:48
  • Yes, since the process is run before the mount command. I took a bind mount as example but it is the same for old kindd of mounts (can be a loop mount with an img file created with dd). – rools Aug 26 '19 at 20:53
2

Call stat(2) on /proc/PID/cwd and on the other directory and compare them by the device:inode tuple.

Example (notice that unless given the -L switch, the stat(1) utility will perform a lstat(2) system call instead of a stat(2)):

$ mkdir -p /tmp/foo /tmp/bar /tmp/baz
$ cd /tmp/foo
$ echo $$
20890

# mount -B /tmp/bar /tmp/foo
# stat -Lc %d:%i /proc/20890/cwd
2055:1835959

# stat -Lc %d:%i "$(readlink /proc/20890/cwd)" /tmp/foo /tmp/bar
2055:1843068
2055:1843068
2055:1843068

# umount /tmp/foo
# stat -Lc %d:%i /tmp/foo
2055:1835959

Just like the files under /proc/PID/fd, /proc/PID/cwd is not a real symlink -- an open(2), stat(2), etc. will not follow its target, but act directly on the actual object it refers to.

| improve this answer | |
  • Nice! I did not even think about stat since ls was giving me the info. Thanks to the deferencing from stat and thank you. – rools Aug 27 '19 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.