为什么我们不能在Linux中通过system()系统调用来更改目录? [英] Why can't we change directories through system() system call in Linux?

查看:95
本文介绍了为什么我们不能在Linux中通过system()系统调用来更改目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

system ("cd ..");

这不会产生任何错误,但也不会做任何有意义的事情.为什么?

This doesn't produce any error but also doesn't do anything meaningful. Why?

推荐答案

system()函数使fork()创建一个进程,该进程是初始进程的副本.

The system() function makes a fork() that creates a process being a copy of the initial one.

当前目录取决于进程的环境(存储在进程的环境变量中).因此,当具有自己环境的 child 进程生成一个cd时,该进程仅影响 child 进程,而不影响父进程.

The current directory depends on the environment of a process (it is stored within the environment variables of a process). Thus when the child process, having its own environment, makes a cd, that affects only the child process, not the parent.

  • 父进程:/home/x/y

  • Parent process: in /home/x/y

子进程(在派生之后):在/home/x/y

Child process (after the fork): in /home/x/y

在子进程中执行cd ..会将其本地环境设置为/home/x
但是父进程仍位于/home/x/y

Doing a cd .. in the child process sets its local environment to /home/x
But the parent process is still in /home/x/y

父进程等待 child 完成system调用,然后在不改变其自身环境(当前目录)的情况下继续执行自己的执行.

Parent process waits for child to complete the system call, then continue its own execution having its own environment (current directory) unchanged.

这篇关于为什么我们不能在Linux中通过system()系统调用来更改目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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