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

后端 未结 5 2054
醉酒成梦
醉酒成梦 2020-12-07 01:30

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

5条回答
  •  无人及你
    2020-12-07 01:48

    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().

提交回复
热议问题