问题
Is it possible to change around directories using the fork command? Without going too much into my code I have the following:
childpid = fork();
if (childpid >= 0)
{
if (childpid == 0)
{
ret = execvp(argv[0],argv);
exit(ret);
} else {
waitpid(childpid,&status,0);
ret = WEXITSTATUS(status);
}
}
The above works fine when I'm entering basic command like ls
, pwd
, etc.. Is it possible to implement a way to use the cd function? I can type the command cd ..
but it doesn't do anything.
For example if my program is in /Users/username/Desktop/
I would like to use commands such as cd ..
to go into /Users/username/
or be able to go straight into /Users
I've seen some stuff about chdir
but I'm not sure exactly how it works/how to use it.
回答1:
As you mentionned chdir is the best way to change the working directory of the current process, a shell command cd
would only change the working directory of of the process running the command ( and not the parent process ) as fork
would create a new process.
for chdir usage you could try :
#include <stdio.h>
#include <unistd.h>
int main() {
char cwd[4096];
fputs(getcwd(cwd,4096),stdout); // will print the current working directory
fputs("\n",stdout);
chdir("/"); // change directory
fputs(getcwd(cwd,4096),stdout); // print new working directory
fputs("\n",stdout);
}
来源:https://stackoverflow.com/questions/38579233/using-cd-command-with-fork-in-c