如何在Linux中使用chdir函数? [英] How can I use chdir function in Linux?

查看:1086
本文介绍了如何在Linux中使用chdir函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,这是我在testchdir.c文件中的原始代码:

I have a question, here is my original code in the testchdir.c file:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc,char **argv) 
{ 
    if (argc < 2)
    {
        printf("Usage: %s <pathname\n",argv[0]);
        exit(1);
    }

    if (chdir(argv[1]) == 0)
    {
        printf("success in chdir\n");
        return 0;
    }
    else
    {
        printf("error happened");
        exit(1);
    }
}

在我的Linux系统中,我的原始路径为/home/Tom3543,然后当我使用gcc -o testchdir testchdir.c编译以上代码时,它看起来不错.稍后,我想更改路径并执行程序,所以输入

In my Linux system, my original path is /home/Tom3543, then when I compile my codes above using gcc -o testchdir testchdir.c, it looks good. Later on, I want to change my path and execute the program, so I type

./testchdir /home/tom3543/C++

"chdir成功"出现在我的终端中,但是我的路径仍然是/home/Tom3543.有人可以帮我解释原因吗?我对此感到困惑!

"success in chdir" appeared in my terminal, but my path is still /home/Tom3543 in my terminal. Can someone help me explain why? I am confused about that!

推荐答案

这是因为shell为您的程序启动了 new 进程,而您仅在该新进程中更改了当前目录.外壳程序不会受到影响.

It's because the shell starts a new process for your program, and you only change the current directory in that new process. The shells process will be unaffected.

不幸的是(对您而言)没有真正好的(或合法的)方式来更改父进程(shell的进程)的工作目录.

Unfortunately (for you) there's no real good (or legal) way to change the working directory of the parent process (the process of the shell).

这篇关于如何在Linux中使用chdir函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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