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

前端 未结 3 1213
傲寒
傲寒 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 09:39

    That's because it executes another shell. Inside this shell, the working directory changes, but that has no effect on the calling program.

    0 讨论(0)
  • 2021-01-07 09:54

    system runs the command you passed it in a different process (in a subshell). That subshell changes directories and promptly exits.

    That's all perfectly valid, but perfectly useless. Use chdir to change your working directory.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题