本文針對 Linux/UNIX 環境下幾個常用函數——pthread_create、readlink、getpid、strrchr 與 strstr——做詳細的整理與說明。
函數原型:
#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_rtn)(void *),
void *restrict arg);
成功時回傳 0,失敗則回傳錯誤編號。成功後,tidp 指向的記憶體會被設為新執行緒的 ID;attr 用於設定各種執行緒屬性;新執行緒會從 start_rtn 函數的位址開始執行,並接收唯一參數 arg。若需傳入多個參數,應先打包進結構體再傳入其位址。
補充:由 restrict 修飾的指標,代表它是唯一存取該物件的方法,這能幫助編譯器進行更積極的優化。另外,編譯時務必加上 -lpthread 參數以連結函式庫,因為 pthread 並非 Linux 的預設函式庫。
#include <unistd.h>
int readlink(const char *path, char *buf, size_t bufsiz);
此函數會將 path 的符號連結內容複製到 buf 所指的記憶體,回傳字元數(不含 NULL 結尾)。若 bufsiz 小於連結內容長度,多出的部分會被截斷。執行失敗回傳 -1,錯誤碼存於 errno,常見錯誤包含 EACCES(權限不足)、EINVAL、EIO、ELOOP、ENAMETOOLONG、ENOENT、ENOMEM、ENOTDIR 等。
搭配 /proc/self/exe 即可取得目前程式的執行路徑:
#include <stdio.h>
#include <unistd.h>
#define PATH_MAX 1024
char * get_exe_path() {
static char buf[PATH_MAX];
int i;
int rslt = readlink("/proc/self/exe", buf, PATH_MAX);
if (rslt < 0 || rslt >= PATH_MAX) {
return NULL;
}
buf[rslt] = '\0';
for (i = rslt; i >= 0; i--) {
if (buf[i] == '/') {
buf[i + 1] = '\0';
break;
}
}
return buf;
}
#include <unistd.h>
pid_t getpid(void);
用來取得目前進程的 PID。許多程式會用它來建立暫存檔名稱,以避免檔名衝突。
#include <unistd.h>
int main() {
printf("pid=%d\n", getpid());
return 0;
}
char *strrchr(char *str, char c);
找出字元 c 在字串中「最後一次」出現的位置,並回傳從該位置到字串結尾的所有字元;找不到則回傳 NULL。
#include <string.h>
#include <stdio.h>
int main(void) {
char string[16];
char *ptr, c = 'r';
strcpy(string, "This is a string");
ptr = strrchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr - string);
else
printf("The character was not found\n");
return 0;
}
在 str1 中搜尋 str2 首次出現的位置,找到則回傳該處指標,否則回傳 NULL。
char st[] = "abc 1234 xyz";
printf("%s", strstr(st, "34")); // 輸出:34 xyz