Changing directory in a pthread
Asked Answered
U

1

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.

Undergrown answered 11/6, 2013 at 20:56 Comment(0)
S
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.

Subteen answered 12/6, 2013 at 5:53 Comment(1)
Thank you very much ,i'm working on linux ,the unshare function is perfect to do this.Undergrown

© 2022 - 2024 — McMap. All rights reserved.