Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing directory in a pthread

Tags:

pthreads

chdir

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.

like image 240
badr assa Avatar asked Jun 11 '13 20:06

badr assa


1 Answers

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.

like image 188
caf Avatar answered Sep 23 '22 14:09

caf