讀取和修改 /proc 目錄下的文件
示例程序:訪問/proc/sys/kernel/pid_max文件(TLPI_12-1)
#include <fcntl.h>
#include "tlpi_hdr.h"
#define MAX_LINE 100
int
main(int argc, char *argv[])
{
int fd;
char line[MAX_LINE];
ssize_t n;
fd = open("/proc/sys/kernel/pid_max", (argc > 1) ? O_RDWR : O_RDONLY);
if (fd == -1)
errExit("open");
n = read(fd, line, MAX_LINE);
if (n == -1)
errExit("read");
if (argc > 1)
printf("Old value: ");
printf("%.*s", (int) n, line);
if (argc > 1) {
if (lseek(fd, 0, SEEK_SET) == -1)
errExit("lseek");
if (write(fd, argv[1], strlen(argv[1])) != strlen(argv[1]))
fatal("write() failed");
system("echo /proc/sys/kernel/pid_max now contains "
"`cat /proc/sys/kernel/pid_max`");
}
exit(EXIT_SUCCESS);
}
Line23:
printf()中“%s”表示輸出格式爲字符串,而形如“%.6s”則表示輸出指定字符串的前6個字符,
“%.*s”表示輸出指定字符串的前*個字符,而*的實際數字則由printf()函數第二個參數指出,上面的代碼中 n 爲read()函數執行完後返回的實際讀取的字節數,即字符個數,其類型爲ssize_t, 屬於有符號的整數類型,將其強制轉換爲int類型作爲上述第二個參數。
Line32/33:
Defined in header <stdlib.h> |
---|
int system( const char *command ); |
在Linux下用來執行shell命令。更多有關內容參考http://blog.sina.com.cn/s/blog_8043547601017qk0.html