使用chdir()从终端改变目录 [英] Using chdir() to change directory from Terminal

查看:168
本文介绍了使用chdir()从终端改变目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 CHDIR()来改变目录作为参数传递给这个函数传递的值。

I am using chdir() to change directory to the value passed as an argument to this function.

我明白,当我使用我的运行C程序 GCC myCd.c ./ a.out的.. 这将改变C程序中的目录的父目录(即一个子进程产生了a.out的进程和目录的变化子进程中发生)。

I understand that when I run my C program using gcc myCd.c and ./a.out .. this changes the directory to the parent directory "within" the C program (i.e. a child process is spawned for the a.out process, and the change of directory happens within that child process).

我想要做的是,在使用该C程序更改终​​端上的目录。我试着写一个shell脚本为同一个,然后是采购和运行,该作品,但我想实现这一目标用C

What I want to do is, change the directory at the terminal using this C program. I tried writing a shell script for the same, and then sourcing it, and running, that works, but I wanted to achieve this using C.

推荐答案

你所试图做无法做到的。该的当前工作目录的是每个进程的属性。

What you are attempting to do can't be done. The current working directory is a per-process attribute.

如果你运行一个程序,它改变它的 CWD 的,它不会影响任何其他进程,除了任何孩子可能在 CHDIR后创建()

If you run a program which changes its cwd, it does not affect any other processes, except for any children it might create after the chdir().

要改变终端的工作目录正确的方法是使用 CD 命令,该命令shell将执行代表你,并保持在同一进程中。也就是说, CD 是几个命令的一个shell不会叉();这使得 CD 命令按预期方式工作。

The correct way to change the terminal's working directory is to use the cd command which the shell executes on your behalf and remains within the same process. That is, cd is one of several commands that the shell does not fork(); this makes the cd command work as expected.

ING一个shell文件使得外壳的进程中运行。但是,如果你在没有运行脚本,你会发现有完全相同的问题与C程序:外壳叉以创建一个进程脚本运行,它运行,然后退出,然后壳继续,但是没有其CWD改变。

sourceing a shell file makes it run within the shell's process. However, if you were to run the script without source, you'd find there was the exact same problem as with a C program: the shell forks to create a process for the script to run, it runs and then exits, and then the shell continues, but without its cwd changed.

这篇关于使用chdir()从终端改变目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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