File: chdirsaf.c

package info (click to toggle)
patch 2.7.6-3%2Bdeb10u1
  • links: PTS
  • area: main
  • in suites: buster
  • size: 6,988 kB
  • sloc: ansic: 40,033; sh: 6,547; yacc: 1,842; makefile: 140; sed: 54
file content (35 lines) | stat: -rw-r--r-- 580 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* A safer version of chdir, which returns back to the
   initial working directory when the program exits.  */

#include <config.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

static char *initial_wd;

static void
restore_wd (void)
{
  chdir (initial_wd);
}

int
chdir_safer (char const *dir)
{
  if (! initial_wd)
    {
      size_t s;
      for (s = 256;  ! (initial_wd = getcwd (0, s));  s *= 2)
	if (errno != ERANGE)
	  return -1;
      if (atexit (restore_wd) != 0)
	{
	  free (initial_wd);
	  initial_wd = 0;
	  return -1;
	}
    }

  return chdir (dir);
}