Using the exec () family to run the cd command

I know that cd is an inline shell, and I can run it using system() .

But is it possible to run the cd for the exec() family, for example execvp() ?

Edit: And I just noticed that system("cd") also pointless. Thanks for helping everyone.

+4
source share
5 answers

exec downloads the executable file and replaces it with the current sample program. As you rightly pointed out, cd not an executable file, but rather an embedded shell. Thus, the executable you want to run is the shell itself. This, of course, is what system() does for you, but if you want to be explicit, you can use exec :

 execl("/bin/sh", "-c", "cd", (const char *)0); 

Since this replaces your current process image, you should do this after fork() from the new process.

However, this entire procedure has absolutely no effect. If you want to change the directory in the current process, use chdir() .

+10
source

You better use int chdir(const char *path); found in unistd.h .

+10
source

Until, as already mentioned, system("cd xxx") changes your current application directory, it will not be completely useless.

You can still use the system exit status to find out if the current directory will be changed to the specified one or not.

Similarly, if you like complex solutions, you can also do the same with fork / exec, either using exec'ing /bin/sh -c cd xxx , or just /bin/cd xxx from the OS that provides an independent executable cd .

I would recommend that this non overkill the faster equivalent of access("xxx", X_OK|R_OK)

Note. All POSIX compatible operating systems must provide an independent executable cd file. This is at least with Solaris , AIX , HP-UX, and Mac OS / X.

+3
source

No, it is not, and it is useless. chdir (a function that changes the current directory of a process) only affects the process that calls it (and its children). This does not affect his parent in particular.

So, exec ing cd does not make sense, since the process will be immediately after changing directories.

(You can do something like bash -c cd /tmp if you want, but as I said, it is fruitless.)

+2
source

When fork is running, the CWD environment variable (current working directory) is inherited by the child of the parent. If fork and exec are executed as usual, then the child calls chdir (), which simply changes the directory to the new directory and exits, but this does not affect the parent. Reason, the new environment is lost.

0
source

Source: https://habr.com/ru/post/1403311/


All Articles