Use more efficient way of restoring working directory
Rather than using a string-based path, we can restore the working
directory via a file descriptor and use of fchdir().
From the getcwd manpage:
Opening the current directory (".") and calling fchdir(2) to
return is usually a faster and more reliable alternative when
sufficiently many file descriptors are available.
/* save the cwd so we can restore it later */
- if(getcwd(cwd, PATH_MAX) == NULL) {
+ do {
+ cwdfd = open(".", O_RDONLY);
+ } while(cwdfd == -1 && errno == EINTR);
+ if(cwdfd < 0) {
_alpm_log(handle, ALPM_LOG_ERROR, _("could not get current working directory
"));
- } else {
- restore_cwd = 1;
}
/* libarchive requires this for extracting hard links */
@@ -607,8 +608,12 @@ static int commit_single_pkg(alpm_handle_t *handle, alpm_pkg_t *newpkg,
archive_read_finish(archive);
/* restore the old cwd if we have it */
- if(restore_cwd && chdir(cwd) != 0) {
- _alpm_log(handle, ALPM_LOG_ERROR, _("could not change directory to %s (%s)
"), cwd, strerror(errno));
+ if(cwdfd >= 0) {
+ if(fchdir(cwdfd) != 0) {
+ _alpm_log(handle, ALPM_LOG_ERROR,
+ _("could not restore working directory (%s)
"), strerror(errno));
+ }
+ close(cwdfd);
}
/* save the cwd so we can restore it later */
- if(getcwd(cwd, PATH_MAX) == NULL) {
+ do {
+ cwdfd = open(".", O_RDONLY);
+ } while(cwdfd == -1 && errno == EINTR);
+ if(cwdfd < 0) {
_alpm_log(handle, ALPM_LOG_ERROR, _("could not get current working directory
"));
- } else {
- restore_cwd = 1;
}
/* just in case our cwd was removed in the upgrade operation */
@@ -365,10 +366,14 @@ int _alpm_unpack(alpm_handle_t *handle, const char *archive, const char *prefix,
cleanup:
umask(oldmask);
archive_read_finish(_archive);
- if(restore_cwd && chdir(cwd) != 0) {
- _alpm_log(handle, ALPM_LOG_ERROR, _("could not change directory to %s (%s)
"),
- cwd, strerror(errno));
+ if(cwdfd >= 0) {
+ if(fchdir(cwdfd) != 0) {
+ _alpm_log(handle, ALPM_LOG_ERROR,
+ _("could not restore working directory (%s)
"), strerror(errno));
+ }
+ close(cwdfd);
}
+
return ret;
}
int _alpm_run_chroot(alpm_handle_t *handle, const char *path, char *const argv[])
{
- char cwd[PATH_MAX];
pid_t pid;
- int pipefd[2];
- int restore_cwd = 0;
+ int pipefd[2], cwdfd;
int retval = 0;
/* save the cwd so we can restore it later */
- if(getcwd(cwd, PATH_MAX) == NULL) {
+ do {
+ cwdfd = open(".", O_RDONLY);
+ } while(cwdfd == -1 && errno == EINTR);
+ if(cwdfd < 0) {
_alpm_log(handle, ALPM_LOG_ERROR, _("could not get current working directory
"));
- } else {
- restore_cwd = 1;
}
/* just in case our cwd was removed in the upgrade operation */
@@ -598,8 +602,12 @@ int _alpm_run_chroot(alpm_handle_t *handle, const char *path, char *const argv[]
}