以编程方式更改进程的当前工作目录 [英] Changing a process's current working directory programmatically

查看:135
本文介绍了以编程方式更改进程的当前工作目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一番研究,我意识到 cd 系统命令在我的系统上没有任何实现文件,特别是在/bin/中.一个类项目最近需要实现一个基本的shell程序,该程序可以利用此目录中的实现文件.

After a bit of research I realized that the cd system command does not have any implementation files on my system, specifically in /bin/. A class project recently required the implementation of a basic shell program that could make use of the implementation files located in this directory.

因此,我的程序无法更改目录,因为 cd 不存在,并且必须是其他shell的内部实现.

Consequentially, my program cannot change directories since cd does not exist and must have been an internal implementation by other shells.

话虽如此,您将如何以编程方式更改程序的当前工作目录?

That being said, how would you go about programmatically changing the current working directory of a program?

推荐答案

每个单独的进程都有其当前目录"的概念.创建新进程时,其当前目录是其父进程的当前目录.

Each individual process has a notion of its "current directory". When a new process gets created, its current directory is its parent process's current directory.

shell只是另一个进程,与任何其他进程都没有什么不同,除了该特定进程等待您键入命令,然后将键入的命令作为新进程执行.

A shell is just another process, no different from any other process, except that this particular process waits for you to type a command, then it executes the typed command as a new process.

现在应该清楚为什么没有任何实际的"cd"命令.说有一个.因此,您键入"cd"命令,然后外壳程序将"cd"命令作为新进程执行.

It should now become obvious why there isn't any actual "cd" command. Say there was one. So, you typed the "cd" command, and the shell executes the "cd" command as a new process.

新进程更改其当前目录,然后退出.

The new process changes its current directory, and exits.

那么,您完成了什么?绝对没有.Shell的当前目录未更改.在这个假设的情况下,cd"进程所做的只是改变它自己的当前目录,没有别的.然后终止,一切恢复到以前的样子.

So, what did you accomplish? Absolutely nothing. The shell's current directory has not changed. All that the "cd" process would do, in this hypothetical case, is change its own current directory, and nothing else. Then it terminates, and everything's back to the way it was before.

这就是为什么"cd"是内置命令的原因.此命令是直接由Shell执行的几个命令之一,此命令可更改Shell的当前目录.因此,从该Shell启动的所有未来进程现在都将拥有一个新的当前目录.

That's why "cd" is a built-in command. This command is one of several commands that's executed by the shell directly, and this command changes the shell's current directory. So, all future processes started from this shell will now have a new current directory.

更改进程当前目录的系统调用为 chdir(2).C,Perl,Python和几乎所有其他编程语言在chdir或类似的地方都有一些功能,该功能执行更改该进程当前目录的系统调用.

The system call that changes the process's current directory is chdir(2). C, Perl, Python, and pretty much every other programming language has some function somewhere called chdir, or something similar, that executes the system call that changes the process's current directory.

这篇关于以编程方式更改进程的当前工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆