Why can't we change directories through system() system call in Linux?

前端 未结 3 1216
傲寒
傲寒 2021-01-07 09:30
system (\"cd ..\");

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

3条回答
  •  無奈伤痛
    2021-01-07 10:04

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

    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.

    • Parent process: in /home/x/y

    • Child process (after the fork): in /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

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

提交回复
热议问题