如何在C的我自己的shell中实现cd命令? [英] How can I implement cd command in my own shell in C?

查看:614
本文介绍了如何在C的我自己的shell中实现cd命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,我是一名西班牙学生,我无法正确解释,但是,我需要在自己的C语言shell中实现cd命令. 适用于工作班,如果有人可以帮助实现它. 当我将if条件置于进程中时,cd无法正常工作,但是当我将代码置于外部时,cd才能正常工作,但是,当放回cd时,它不会像cd命令通常那样返回到先前的目录.

如果可以纠正失败,请执行以下操作.非常感谢你.

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h> 
#include <unistd.h> 
#include <libgen.h> 
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>

#define TAM 1000 

void  parseo(char *line, char **argv);

int main(void) {

    char  cad[TAM];             
    char  *argv[TAM]; 
    char  *gdir;
    char  *dir;
    char  *to;
    char buf[TAM];
    pid_t pid;
    int status;

    while (1) {                   

        printf("user@PC: ");    
        fgets(cad, 1000, stdin);

        // Si encontramos un salto de linea (se pulsa enter)
        if (cad[strlen(cad) - 1] == '\n')                                                           
            cad[strlen(cad) - 1] = '\0';    // lo marcamos como final de sentencia            

        parseo(cad, argv);


        // Exit para salir del shell
        if (!strcmp(argv[0], "exit")) exit(0);  

        if (!strcmp(argv[0], "cd")){

            gdir = getcwd(buf, sizeof(buf));
            dir = strcat(gdir, "/");
            to = strcat(dir, argv[1]);

            chdir(to);
            //printf("Acceso a la carpeta realizado\n");

        }            

        pid = fork();

        if (pid == 0) {   

            if (execvp(*argv, argv) < 0) {
                printf("%s: no se encontró la orden \n", argv[0]);
                exit(1);
            }
        }else {  

            waitpid(pid,&status,0);
        }   

    }
    return 0;
}

void  parseo(char *line, char **argv){

    while (*line != '\0') {       
        while (*line == ' ' || *line == '\t' || *line == '\n')

            *line++ = '\0';     
            *argv++ = line; 

        while (*line != '\0' && *line != ' ' && *line != '\t' && *line != '\n') 
            line++;             
    } 
    *argv = '\0';             // marca de final
}

解决方案

实际上运行良好!唯一的问题是,在调用chdir()之后,您的代码将继续将命令解析为外部可执行文件,这将失败.您对于exit并没有此问题,因为它在执行其他任何操作之前先退出外壳. :)

将紧随其后的代码移到else块中,或在chdir()之后添加continue,应该对其进行修复.

(顺便说一句:chdir()之前的getcwd()/strcat()步骤实际上是不必要的.chdir()使用相对路径:例如,如果当前工作目录为/usr,则可以调用chdir("bin")进入/usr/bin.)

this is my code, i'm a Spanish student and I can't explain correctly, but, i need implement cd command in my own shell in C. Is for a workclass, if someone can help for realize it. When I put the if condition on process, cd doesn't work, But when I put the code outside I get the cd to work, however, when putting back cd does not return to the previous directory as the cd command would normally do.

If any can correct the fail. Thanks you so much.

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h> 
#include <unistd.h> 
#include <libgen.h> 
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>

#define TAM 1000 

void  parseo(char *line, char **argv);

int main(void) {

    char  cad[TAM];             
    char  *argv[TAM]; 
    char  *gdir;
    char  *dir;
    char  *to;
    char buf[TAM];
    pid_t pid;
    int status;

    while (1) {                   

        printf("user@PC: ");    
        fgets(cad, 1000, stdin);

        // Si encontramos un salto de linea (se pulsa enter)
        if (cad[strlen(cad) - 1] == '\n')                                                           
            cad[strlen(cad) - 1] = '\0';    // lo marcamos como final de sentencia            

        parseo(cad, argv);


        // Exit para salir del shell
        if (!strcmp(argv[0], "exit")) exit(0);  

        if (!strcmp(argv[0], "cd")){

            gdir = getcwd(buf, sizeof(buf));
            dir = strcat(gdir, "/");
            to = strcat(dir, argv[1]);

            chdir(to);
            //printf("Acceso a la carpeta realizado\n");

        }            

        pid = fork();

        if (pid == 0) {   

            if (execvp(*argv, argv) < 0) {
                printf("%s: no se encontró la orden \n", argv[0]);
                exit(1);
            }
        }else {  

            waitpid(pid,&status,0);
        }   

    }
    return 0;
}

void  parseo(char *line, char **argv){

    while (*line != '\0') {       
        while (*line == ' ' || *line == '\t' || *line == '\n')

            *line++ = '\0';     
            *argv++ = line; 

        while (*line != '\0' && *line != ' ' && *line != '\t' && *line != '\n') 
            line++;             
    } 
    *argv = '\0';             // marca de final
}

解决方案

It's working fine, actually! The only problem is that, after calling chdir(), your code continues to parse the command as an external executable, which fails. You didn't have this problem for exit because that exits the shell before it can do anything else. :)

Moving the code which follows into an else block, or adding continue after chdir(), should fix it.

(As an aside: The getcwd() / strcat() steps preceding chdir() are actually unnecessary. chdir() works with relative path: for example, if the current working directory is /usr, you can call chdir("bin") to enter /usr/bin.)

这篇关于如何在C的我自己的shell中实现cd命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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