Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

linux - Changing the directory of the shell through a C++ program

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");            
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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. See also getcwd(3), errno(3), credentials(7), proc(5) and path_resolution(7).

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.

You need to read Advanced Linux Programming and syscalls(2).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...