Using the exec() family to run the “cd” command

一曲冷凌霜 提交于 2020-01-19 06:14:04

问题


I know that cd is a shell built-in ,and I can run it by using system().

But is that possible to run the cd command by the exec() family, like execvp()?

Edit: And I just noticed that system("cd") is also meaningless。Thanks for the help of everyone.


回答1:


exec loads an executable file and replaces the current program image with it. As you rightly noted, cd is not an executable file, but rather a shell builtin. So the executable that you want to run is the shell itself. This is of course what system() does for you, but if you want to be explicit about it, 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()ing off a new process.

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




回答2:


You're better off using int chdir(const char *path); found in unistd.h.




回答3:


No it is not, and it would be of no use. chdir (the function that changes a process's current directory) only affects the process that calls it (and its children). It does not affect its parent in particular.

So execing cd has no point, since the process would exit immediately after having changed directories.

(You could exec something like bash -c cd /tmp if you really want to, but as I said, this is fruitless.)




回答4:


While, as already stated system("cd xxx") wouldn't change your application current directory, it is not completely useless.

You can still use system exit status to know if changing your current directory to the one stated would succeed or not.

Similarly, if you like complex solutions, you could also do the same with fork/exec, either with exec'ing /bin/sh -c cd xxx or simply /bin/cd xxx with OSes that provide an independent cd executable.

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

Note: All POSIX compliant OSes must provide an independent cd executable. This is at least the case with Solaris, AIX, HP-UX and Mac OS/X.




回答5:


When a fork is done the environment variable CWD(current working directory) is inherited by the child from the parent.If fork and exec is done 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.Hence, the new environment is lost..



来源:https://stackoverflow.com/questions/9859903/using-the-exec-family-to-run-the-cd-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!