Is it possible to use chdir() or some other command to change the directory in a thread without affecting the cwd of the other threads ? I'm using pthread.h.

*I'm trying to write a server program that handles multiple client connections and requests. One of the available commands to the client is the 'cd' command.

有帮助吗?

解决方案

No, as mentioned by others the current working directory is a per-process property, not per-thread. You can "emulate" a per-thread (or per client, or however you structure your application) current working directory by storing a file descriptor for the "per-thread CWD" and the using the various *at() syscalls specified in POSIX 2008 (openat() etc.) to manipulate paths relative to that directory fd.

其他提示

No, it isn't. The current working directory is a process wide setting, not a thread setting.

Your best bet is to explicitly access files in a directory using the full path, rather than changing to that directory in order to do so.

Answering the updated question:

For each client you will need a client structure, which amongst other things (Id, Ip, anything you might consider important) also holds the directory the client is visualizing right now (assuming you do something like this).

So when a request from the client comes you already know in which directory that client works.

On some platforms, the answer is yes. While the POSIX standard specifies the current working directory as per-process not per-thread, some platforms provide a per-thread working directory as a non-standard extension. To my knowledge, the only platforms having this feature are Linux and XNU (macOS/iOS/etc), although their APIs for setting the per-thread working directory are fundamentally incompatible with each other. If those are the only platforms you need to support, you could use their per-thread working directory support.

However, it would mean your software (or this aspect of it) would be fundamentally non-portable – it is never going to work on Windows, Cygwin, FreeBSD/OpenBSD/NetBSD, Solaris/Illumos, AIX, etc, since those platforms lack the concept of a per-thread working directory. It is possible one or more of them may add that support in the future, but there's no guarantee that will happen for any of them, and it could be years away even if it does.

In terms of details of the Linux and Apple APIs to do this, I explained it in my answer to another question, so I won't repeat those details here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top