Closed. This question is off-topic. It is not currently accepting answers. Learn more
想改进这个问题吗?Update the question所以堆栈溢出的值小于aa>。
在我们的应用程序中,我们调用getcwd(3)来获取当前的工作目录。
当进程开始运行时,如果有人删除了目录路径,则进程正在运行,但getcwdapi失败(返回NULL)。
例子:
进程名为:a.exe存在于/root/appl/a.exe
运行a.exe后,如果删除当前工作目录,getcwd(3)api将失败。
是否有其他api可以让getcwd(3)知道进程的当前工作目录,即使目录路径已删除?

最佳答案

我不太清楚当目录被打开时,目录将继续存在的时候,你将如何处理当前工作目录的结果——你不能在目录中创建新文件,它必须是空的,所以它可以被删除——但是你可以使用readlink(2) on /proc/self/cwd发现名称:

$ mkdir syedsma
$ cd syedsma/
$ /tmp/proccwd
/proc/self/cwd reports: /tmp/syedsma
$ /tmp/getcwd
getcwd: /tmp/syedsma
$ rmdir ../syedsma/
$ /tmp/getcwd
getcwd failed: No such file or directory
$ /tmp/proccwd
/proc/self/cwd reports: /tmp/syedsma (deleted)
$

这是我的getcwd.c
#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
    char p[1000];
    char *r;
    r = getcwd(p, sizeof(p));
    if (!r)
        perror("getcwd failed");
    else
        printf("getcwd: %s\n", p);
    return 0;
}

这是我的proccwd.c
#include <stdio.h>
#include <unistd.h>
#include <limits.h>

int main(int argc, char* argv[]) {
    char buf[PATH_MAX];

    ssize_t r = readlink("/proc/self/cwd", buf, sizeof(buf));

    if (r < 0) {
        perror("readlink /proc/self/cwd failed");
        return 1;
    } else {
        buf[PATH_MAX-1] = '\0';
        printf("/proc/self/cwd reports: %s\n", buf);
    }
    return 0;
}

mu is too short如果他是一个守护进程,那么他对chdir("/");的建议是正确的。我可以想象,你可能有一个很好的理由让你的程序知道它当前的工作目录,甚至有一个路径名可能是什么如果它仍然存在的想法-但一般来说,你不应该关心。路径名"."将在几乎所有需要当前工作目录的情况下工作,直到您需要为用户实现一个内置的pwdshell。

07-28 02:56
查看更多