How to change directory in terminal from a C file

前端 未结 1 1526
半阙折子戏
半阙折子戏 2021-01-27 08:05

How to change the directory from a C program that will effect on the terminal.

Actually don\'t tell about system(\"\") function or chdir(\"\") function. Those work only

相关标签:
1条回答
  • 2021-01-27 08:21

    You don't. You cannot (*). The working directory is an attribute of a process. The terminal hosts a shell; that's a process. Your program is another process. Never the twain shall meet.

    However, you are solving the wrong problem. Assume that you have a C program that converts an inode number to a path, and then prints the resulting path to standard output. Now, all you need is a shell alias that runs cd $(my-program $1), and there you are -- a shell command that cd's by inode.

    (*) If you write a program to attach to the shell process with ptrace, and you have the necessary permissions, you might be able to force the shell to change its working directory. However, since the shell in particular is maintaining things like PWD, the result of this may be incompletely effective.

    You could write a shell function that ran at each prompt that checked for a file; if the file existed, the function would read it and set the working directory to the path in it. Probably this is not what you had in mind.

    Since the shells you are using are open source (probably bash, perhaps zsh or fish), you might also consider making your own fork and adding your own extremely slow shell command that maps inode numbers to directories and cd's to them.

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