This question already has an answer here:
- Change directory of parent process after exit [duplicate] 2 answers
I have a program that calls chdir() to change the cwd. However, after the program finishes the cwd changes back to the directory that called the program instead of staying the in one specified by the call to chdir(). I made a program to test if chdir() is actually changing to the specified directory and found that chdir() is doing what I presumed: changing to the specified directory for the duration of the program then returning to the directory that executed the program.
Here is the code for the test:
#include <stdio.h>
#include <unistd.h>
#define NAME_MAX 100
int main(int argc, char **argv)
{
char buf[NAME_MAX];
char *path = argv[1];
if (chdir(path) == -1) { /* change cwd to path */
fprintf(stderr, "error: could not change to dir %s\n", path);
return 1;
}
getcwd(buf, NAME_MAX);
printf("CWD is: %s\n", buf); /* print cwd as obtained from getcwd() */
return 0;
}
and here is the output from my terminal:
john@ubuntu:~/C/cli$ pwd
/home/john/C/cli
john@ubuntu:~/C/cli$ mkdir foobar
john@ubuntu:~/C/cli$ ./test.c foobar
CWD is: /home/john/C/cli/foobar
john@ubuntu:~/C/cli$ pwd
/home/john/C/cli
So my question is, how can I stay in the directory that I specify in the call to chdir() after the the program finishes? Also, I am on Ubuntu 12.04 and compiling with gcc.