linux如何获取当前进程的工作目录
时间: 2023-07-19 08:03:51 浏览: 42
可以使用系统调用 `getcwd()` 获取当前进程的工作目录。
具体的使用方法如下:
```c
#include <unistd.h>
#include <stdio.h>
int main() {
char buffer[1024];
if (getcwd(buffer, sizeof(buffer)) != NULL) {
printf("Current working directory: %s\n", buffer);
} else {
perror("Error getting current working directory");
return 1;
}
return 0;
}
```
其中,`getcwd()` 函数的第一个参数是一个字符数组,用来存储当前工作目录的路径,第二个参数是字符数组的大小。如果函数调用成功,返回值为指向当前工作目录的指针;否则返回 NULL。
上述代码中,如果 `getcwd()` 函数调用成功,则将当前工作目录路径打印出来;否则输出错误信息。
相关问题
linux 改变当前进程的工作目录
要改变当前进程的工作目录,可以使用 chdir() 函数。该函数的原型为:
```c
#include <unistd.h>
int chdir(const char *path);
```
其中,path 参数为要改变到的目标目录的路径名。调用成功时返回 0,发生错误时返回 -1。
例如,要将当前进程的工作目录改变为 /home/user 目录,可以这样调用 chdir() 函数:
```c
chdir("/home/user");
```
linux获取当前进程pid
您可以使用 Linux 命令 "pidof" 或者 "ps" 来获取当前进程的 PID。如果您想获取某个特定进程的 PID,可以使用 "ps -ef | grep <process_name>" 的命令来查找。这个命令会列出所有包含"<process_name>"的进程信息,其中包括进程的 PID。