鍍金池/ 問答/Java  Linux  網(wǎng)絡(luò)安全/ [apue]函數(shù)getcwd示例疑問

[apue]函數(shù)getcwd示例疑問

apue第三版中文版4.23節(jié)
先是一個(gè)chdir的例子講了執(zhí)行該程序后無法更改當(dāng)前目錄:

#include "apue.h"

int
main(void)
{
    if (chdir("/tmp") < 0)
        err_sys("chdir failed");
    printf("chdir to /tmp succeeded\n");
    exit(0);
}

然后先顯示pwd 接著執(zhí)行./a.out 然后pwd發(fā)現(xiàn)當(dāng)前目錄沒有切換到/tmp
接著講到getcwd函數(shù),例子:

#include "apue.h"

int
main(void)
{
        char    *ptr;
        size_t          size;

        if (chdir("/usr/lib") < 0)
                err_sys("chdir failed");

        ptr = path_alloc(&size);        /* our own function */
        if (getcwd(ptr, size) == NULL)
                err_sys("getcwd failed");

        printf("cwd = %s\n", ptr);
        exit(0);
}

由于我的ubuntu沒有/usr/spool這個(gè)目錄,所以改成了/usr/lib
getcwd只是獲取了當(dāng)前目錄,但執(zhí)行完之后pwd顯示還是之前的目錄?

回答
編輯回答
夏木

chdir() changes the current working directory of the calling process to the directory specified in path.

man手冊(cè)中說的很清楚了,chdir改變的是調(diào)用進(jìn)程的當(dāng)前工作目錄,而不是你終端的工作目錄。

2017年10月24日 20:20