I'm not entirely sure what you will do with the results of the current working directory when the directory will continue to exist only as long as it is held open -- you can't create new files in the directory, and it had to be empty so it could be deleted -- but you can use readlink(2)
on /proc/self/cwd
to discover the name:
$ 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)
$
Here's my 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;
}
And here's my 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 is correct with his advice to chdir("/");
if it is a daemon -- I can imagine that you might have a good reason for your program to otherwise know its current working directory, and even have an idea of what the pathname might have been if it did still exist -- but in general, you shouldn't care. The pathname "."
will work in just about every case where it makes sense to need the current working directory, until you need to implement a pwd
shell built-in for the user.