我撰寫了一個簡單的程式來測驗 Linux 中每個行程的最大打開檔案數。這里是。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main() {
FILE* fp = NULL;
int count = 0;
while (1) {
fp = fopen("tmp", "w");
if (fp == NULL) {
perror("fopen()");
break;
}
count ;
}
printf("count:%d\n", count);
return 0;
}
我電腦上程式的輸出是
$ ./maxfopen
fopen(): Too many open files
count:1020
我曾經ulimit -a檢查過我電腦上的最大打開檔案數,結果是1024。不出所料,除了stdio、stdout、之外stderr,應該有1021個檔案可以打開,但結果是我電腦上的1020個。怎么了?是否有第四個默認打開檔案流?我怎樣才能檢測到它?
uj5u.com熱心網友回復:
您可以使用strace檢查打開的檔案:
$ strace ./maxfopen 2>&1 | grep AT_FDCWD | wc -l
1024
$ strace ./maxfopen 2>&1 | grep AT_FDCWD
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 4
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 5
...
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 1018
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 1019
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 1020
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 1021
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 1022
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 1023
openat(AT_FDCWD, "tmp", O_WRONLY|O_CREAT|O_TRUNC, 0666) = -1 EMFILE (Too many open files)
所有檔案的總和應該是 (1021 stdin stdout stderr)。如果不是,是因為在 main 函式之前打開了其他檔案,也可以檢查strace。
其他打開(和關閉)的檔案是/etc/ld.so.cache和/lib/x86_64-linux-gnu/libc.so.6(運行程式的動態聯結器)
您可以在以下位置查看檔案描述符來驗證它:/proc/<pid>/fd
uj5u.com熱心網友回復:
它可以被您的 shell 或程式用于其他目的。要準確找出“缺失”的 fd 的用途,您只需在 exit 和 inspect 之前等待/proc/<pid>/fd。
例如,添加一個getchar()并簽/proc/<pid>/fd入另一個終端。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main() {
FILE* fp = NULL;
int count = 0;
while (1) {
fp = fopen("tmp", "w");
if (fp == NULL) {
perror("fopen()");
break;
}
printf("%d\n", fileno(fp)); // shows each fd number
count ;
}
getchar(); // just to keep it running
printf("count:%d\n", count);
return 0;
}
由于fd' 沒有關閉,它們應該指向它們所參考的檔案/設備。
fileno(fp)(參見上面的代碼)還將給出檔案描述符的 fd 編號。因此,您也可以使用它檢查“丟失”的 fd 是什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/431180.html
