6

My question is : How can i change the current directory in a pthread without changing the current directory in other pthreads, I found a solution which is using openat() function, but i didn't found any example explaining how it works. Using chdir() changes the current directory in all pthreads in the process. Thank you for any help.

badr assa
  • 105
  • 1
  • 1
  • 6

1 Answers1

11

The openat() method is an alternative to changing the current working directory. Instead of calling:

chdir("/new/working/directory");
open("some/relative/path", flags);

you instead use:

dirfd = open("/new/working/directory", O_RDONLY | O_CLOEXEC);
openat(dirfd, "some/relative/path", flags);

This is the POSIX-standard way to avoid changing the process-wide current working directory in a thread, but still work with relative paths.

There is a also a Linux-specific way to give the current thread its own current working directory, separate from the rest of the process - unshare(CLONE_FS); - but this is not portable.

caf
  • 233,326
  • 40
  • 323
  • 462