通过C ++程序更改shell的目录 [英] Changing the directory of the shell through a C++ program
问题描述
我想写一个简单的C ++程序来执行Linux命令。我坚持改变目录(命令像 chdir
和 cd
不工作)。这是我到目前为止:
I'm trying to write a simple C++ program to execute Linux commands. I'm stuck at changing the directories (commands like chdir
and cd
don't work). This is what I have so far:
system("echo -n '1. Current Directory is '; pwd");
system("chdir Desktop");
推荐答案
这是不可能的,如果你想改变目录(即 cd
,即 chdir(2) ...)的shell调用了你的程序。因此 cd
必须是 bash(1)内置。
This is not possible, if you want to change the directory (i.e. cd
, that is chdir(2) ...) of the shell which has invoked your program. So cd
has to be a bash(1) builtin.
原因是 chdir
仅影响调用进程(这将是你的C程序)而不是父进程。每个进程都有自己的当前目录。
The reason is that chdir
affects only the calling process (which would be your C program) not the parent process. Each process has its own current directory.
如果调用 system(3)它会 fork(2)新的shell和 execve(2 ) / bin / sh -c
,因此只有分叉的shell可以更改其当前目录。
If you call system(3) it will fork(2) a new shell and execve(2) /bin/sh -c
so only the forked shell can change its current directory.
您需要阅读高级Linux编程。
您可能想要直接在C程序中调用 chdir
。这将影响当前进程和所有未来的子进程(包括在C中的 system
或 popen
代码),直到它们终止或进一步调用 chdir
。但它不会影响你的终端(你开始你的C程序)的shell。
Perhaps you want to call chdir
directly inside your C program. This will affect the current process and all future child processes (including those started with system
or popen
library functions inside your C code) till their termination or some further call to chdir
. But it won't affect the shell in your terminal (where you started your C program).
这篇关于通过C ++程序更改shell的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!