foreword
It is also a very commonly used glibc library function
Whether it is user business code or the code of many class libraries, it will basically be used to obtain the current path
But here we look at the specific implementation
test case
Just simply use getcwd
root@ubuntu:~/Desktop/linux/HelloWorld# cat Test04Getcwd.c
#include "stdio.h"
int main(int argc, char** argv) {
int x = 2;
int y = 3;
int z = x + y;
char* p1 = (char*) malloc(40);
printf("p1 : 0x%x\n", p1);
getcwd(p1, 100);
int p1Len = strlen(p1);
printf(" p1 = %s, p1Len = %d\n ", p1, p1Len);
}
Implementation of getcwd
First confirm the position of the breakpoint, the function call of getcwd in main
The implementation of getcwd is as follows
The default processing is directly based on the getcwd system call
If the name is too long, get the current path based on generic_getcwd
generic_getcwd is based on the proc file system, and obtains the cwd stored in the current process under the proc file system
root@ubuntu:~/Desktop/linux/HelloWorld# ll /proc/5753/cwd
lrwxrwxrwx 1 root root 0 Nov 25 23:39 /proc/5753/cwd -> /root/Desktop/linux/HelloWorld/
getcwd system call
The getcwd system call is as follows, where the current path is "/jerry/dir"
The hard disk "/dev/sda1" is mounted on "/jerry"
The processing here is that the dentry of the current path starts traversing upwards until it hits the root node
Then output this series of paths to the buffer
over