简体   繁体   English

如何从C程序使用exec命令更改目录?

[英]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:

  1. cd is typically a shell builtin command; cd通常是shell内置命令;
  2. on most systems /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; 在具有此功能的极少数系统上,它会更改当前目录,然后生成一个子shell进程;
  3. the current directory is a process' property: if you change the current directory using /bin/cd , you'd lose the directory change as soon as the process terminates; 当前目录是进程的属性:如果使用/bin/cd更改当前目录,则一旦进程终止,您将丢失目录更改;
  4. if you use a function from the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM