[英]how to change directory using exec command from C program?
I have to change working directory from my C program. 我必须从C程序更改工作目录。 For this I have used the following command:
execl("/bin/cd","cd","..",(char*)0);
为此,我使用了以下命令:
execl("/bin/cd","cd","..",(char*)0);
but this command is not changing the directory? 但是此命令不会更改目录吗? Is anything wrong in this command or is there any other way to change working directory from C program?
此命令有什么问题吗,或者有其他方法可以从C程序更改工作目录吗?
To change the current directory you should use chdir
: 要更改当前目录,您应该使用
chdir
:
int chdir(const char *path);
On success it returns 0. 成功返回0。
You can't use execl for several reasons: 由于以下几个原因,您不能使用execl:
cd
is typically a shell builtin command; cd
通常是shell内置命令; /bin/cd
does not exists; /bin/cd
不存在; on the very very few systems that have it, it changes the current directory and then spawns a child shell process; /bin/cd
, you'd lose the directory change as soon as the process terminates; /bin/cd
更改当前目录,则一旦进程终止,您将丢失目录更改; exec
family, the current process image is replaced with a new process image - you could use system
, but wouldn't fix the previous 3 problems. exec
系列中的函数,则当前过程映像将被新的过程映像替换-您可以使用system
,但无法解决前面的3个问题。 What you are doing won't work because the exec
family of calls will actually replace your current program in the current process. 您正在执行的操作将无法正常工作,因为
exec
调用族实际上会在当前进程中替换您当前的程序。 In other words, you will have been terminated so that, when cd
is finished, your parent process will once again take over. 换句话说,您将被终止,以便在
cd
完成时,您的父进程将再次接管。
If you want to change the working directory for the current process, use chdir
. 如果要更改当前进程的工作目录,请使用
chdir
。 If you want to change it on exit, you're out of luck because your program itself is running in a separate process from the parent that started it. 如果要在退出时进行更改,则很不走运,因为程序本身在与启动它的父程序不同的进程中运行。
So, unless you have some form of communication with the parent, that's not going to work. 因此,除非您与家长进行某种形式的交流,否则这将无法正常工作。
您需要使用chdir
系统调用来更改调用进程的工作目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.