2017-06-18 32 views

回答

1

chdir

手冊頁它改變了當前工作目錄

例如

chdir("/home/hello"); 
+0

我知道'chdir()'改變了目錄。這不是問題。 – Melab

2

chdir - 改變工作目錄

#include <unistd.h> 

int chdir(const char *path); 

chdir()改變調用進程的當前工作目錄路徑指定的目錄。

+0

更改當前的工作目錄適合問題,但它本身並不回答。我知道'chdir()'做了什麼。 – Melab

+0

@Melab你的問題不清楚。你想更改爲一個文件名的完整路徑的目錄? – helloV

+0

是的。我的問題很清楚。 – Melab

2

$0在shell腳本中對應於argv[0]在C程序中。但是,如果該命令是基於PATH找到的,則該方法將不起作用。

在Linux中,您可以檢查/proc/self/exe僞符號鏈接以查看當前進程正在執行哪個二進制文件。您可以使用readlink("/proc/self/exe", buffer, size)來獲取當前可執行文件的路徑。

例如,您可以使用例如

#define _POSIX_C_SOURCE 200809L 
#include <stdlib.h> 
#include <unistd.h> 
#include <errno.h> 

/* Return the path to the directory the current executable 
    resides in, as a dynamically allocated string. 
    If an error occurs, returns NULL with errno set. 
*/ 
char *exe_dir(void) 
{ 
    size_t size = 512, i, n; 
    char *path, *temp; 

    while (1) { 
     ssize_t used; 

     path = malloc(size); 
     if (!path) { 
      errno = ENOMEM; 
      return NULL; 
     } 

     used = readlink("/proc/self/exe", path, size); 

     if (used == -1) { 
      const int saved_errno = errno; 
      free(path); 
      errno = saved_errno; 
      return NULL; 
     } else 
     if (used < 1) { 
      free(path); 
      errno = EIO; 
      return NULL; 
     } 

     if ((size_t)used >= size) { 
      free(path); 
      size = (size | 2047) + 2049; 
      continue; 
     } 

     size = (size_t)used; 
     break; 
    } 

    /* Find final slash. */ 
    n = 0; 
    for (i = 0; i < size; i++) 
     if (path[i] == '/') 
      n = i; 

    /* Optimize allocated size, 
     ensuring there is room for 
     a final slash and a 
     string-terminating '\0', */ 
    temp = path; 
    path = realloc(temp, n + 2); 
    if (!path) { 
     free(temp); 
     errno = ENOMEM; 
     return NULL; 
    } 

    /* and properly trim and terminate the path string. */ 
    path[n+0] = '/'; 
    path[n+1] = '\0'; 

    return path; 
} 

請注意,您不一定需要使用chdir()更改爲該路徑;您也可以使用例如open(path, O_PATH)並使用該文件描述符作爲openat()和其他* at()函數的參數。

如果可執行文件在文件系統層次結構中非常深,由於這個僞符號鏈接的性質,這可能會返回NULL與errno == ENAMETOOLONG。替代方法,如閱讀/proc/self/maps/proc/self/smaps的路徑,會遇到未固定的內核錯誤(我已經報道過),其中反斜槓\的路徑得到錯誤的轉義。在任何情況下,如果exe_dir()返回NULL,我熱烈地建議您的程序僅向用戶報告當前可執行文件所在的目錄無法確定(可能與原因一起,strerror(errno)),然後中止。

相關問題