Every process has a current working directory. This directory is where the search for all relative pathnames starts (i.e., with all pathnames that do not begin with a slash(斜线号/)). When a user logs in to a UNIX system, the current working directory normally starts at the directory specified by the sixth field in the /etc/passwd
file — the user ’s home directory(用户登录系统后,当前工作目录都从home目录开始). The current working directory is an attribute of a process; the home directory is an attribute of a login name. (当前工作目录是进程的属性,home目录是登录用户名的属性)
We can change the current working directory of the calling process by calling the chdir
or fchdir
function.
chdir, fchdir - change working directory
#include <unistd.h>
int chdir(const char *path);
int fchdir(int fd);
//Both return: 0 if OK, -1 on error
Example:
作为进程的属性之一,当前工作目录(current working directory)不会影响进程调用chdir
。因此下图的程序不会出现我们预想的结果:
如果我们编译该文件为mycd,并如下操作
$pwd
/usr/lib
$mycd
chdir to /tmp succeeded
$pwd
/usr/lib
会发现执行mycd
的shell的当前工作目录没有改变。这就是shell执行进程的副作用。每个程序运行在不同的进程中,所有在程序中调用chdir
不会影响shell
的当前工作目录。因此,chdir
必须直接由shell
调用,所有cd command
被集合进了shells中去。
因为内核必须要知道当前工作目录,我们需要能够获得当前工作目录的内容。不幸的是,内核不保存目录的完整路径。而是保存了目录的信息,如指向目录的v-node的指针。(LInux可以maintain完整的路径名pathname)
下列函数能活的当前工作目录。
getcwd, getwd, get_current_dir_name - get current working directory
#include <unistd.h>
char *getcwd(char *buf, size_t size);
char *getwd(char *buf);
char *get_current_dir_name(void);
//Returns: buf if OK, NULL on error
getcwd
我们传入缓冲区buffer
的地址,和buffer
的尺寸size
。
buffer
需要足够大到能装下决定路径,加上结尾的null字符。否则会返回错误。
Example:改变工作目录并且显示
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
int main(void)
{
char buf[NAME_MAX];
if(chdir("/home/feather/feather") < 0)//改变工作目录,需要目录存在,不然报错。
{
fprintf(stderr, "chdir error:%s\n", strerror(errno));
exit(-1);
}
if(getcwd(buf, NAME_MAX) < 0)//获得当前的工作目录
{
fprintf(stderr, "getcwd error!\n");
exit(-1);
}
printf("cwd = %s \n", buf);
exit(0);
return 0;
}
注意:如果chdir中参数是symbolic link
那么会跟着进入到链接符号代指的目录。
summary
getcwd
在我们运行的应用程序需要返回到开始执行的位置的时候是很有用的。我们可以在改变工作目录之前调用getcwd
来保存,在我们完成处理之后,通过调用chdir
回到开始的位置。
fchdir
提供了更简单的方法。相对于调用getcwd
,我们可以打开current working directory
并保存文件描述符,之后再跳转到不同的位置。当我们需要返回初始位置的时候,只需要简单的传递file descriptor
到fchdir
中。