Enviar Respuesta  Enviar Tema 
microshell en c
Autor Mensaje
Kira
Usuario PL


Mensajes: 2
Grupo: Registrado
Registro en: Feb 2008
Estado: Sin Conexión
Reputación: 0
Mensaje: #1
microshell en c

hola, me gustaria saber si alguien tiene idea de como puedo crear en c un interprete de ordenes sencillo(interactivo), que permita le ejecucion de ordenes mediante gets(orden) y lo ejecute execvp(orden, vacio). no hace falta que haga analisis sintactico de la orden introducida, y solo ejecutara una orden cada vez. es que lo necesito para una practica y me esta quitando el sueño...

02-18-2008 03:00 PM
Encuentra todos los mensajes de este usuario Cita este mensaje en tu respuesta
p_eter
Chaos Manager
*******
Administrador

Mensajes: 4,131
Grupo: Administrador
Registro en: Jun 2005
Estado: Sin Conexión
Reputación: 11
Mensaje: #2
RE: microshell en c

A ver si algo así te sirve para comenzar:

Código:
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {
        printf ("Pruebe a ejecutar este programa como 'programa ls -l'\n");
        int i;
        printf ("\n Ejecutando el programa (%s). Sus argumentos son: \n", argv[0]);

        for (i=0; i<argc; i++)
                printf ("  argv[%d]: %s \n",i,argv[i]);

        sleep (2);

        /* La  familia de funciones exec reemplaza la imagen del proceso
         * en curso con una nueva. Si cualquiera de las funciones exec
         * regresa, es que ha ocurrido  un  error.
         * Por legibilidad ponemos el código en una claúsula if
         * pero bastaría:
         *      execvp (orden, params, 0);
         *      printf("Error\n");
         *      exit (1);
         * Ya que si llegamos a printf es porque execvp no ha conseguido
         * cambiar la imagen de memoria
         * */
        if (execvp (argv[1],&argv[1])<0) {
                printf("Error en la invocacion\n");
                exit (1);
        }

        // Terminamos
        return 0;
}


http://www2.its.strath.ac.uk/courses/c/
http://www.digilife.be/quickreferences/quickrefs.htm
http://en.wikipedia.org/wiki/C_programming_language
http://guimi.net/index.php?pag_id=cmsxp0...s.html#man


02-18-2008 03:56 PM
Visita el website del usuario Encuentra todos los mensajes de este usuario Cita este mensaje en tu respuesta
Kira
Usuario PL


Mensajes: 2
Grupo: Registrado
Registro en: Feb 2008
Estado: Sin Conexión
Reputación: 0
Mensaje: #3
RE: microshell en c

Ya, pero es que mi problema es que necesito que la ejecución de ordenes sea mediante gets(orden)...

02-20-2008 07:03 AM
Encuentra todos los mensajes de este usuario Cita este mensaje en tu respuesta
p_eter
Chaos Manager
*******
Administrador

Mensajes: 4,131
Grupo: Administrador
Registro en: Jun 2005
Estado: Sin Conexión
Reputación: 11
Mensaje: #4
RE: microshell en c

Código:
/* ----------------------------------------------------------------- */
/* PROGRAM  shell.c                                                  */
/*    This program reads in an input line, parses the input line     */
/* into tokens, and use execvp() to execute the command.             */
/* ----------------------------------------------------------------- */

#include  <stdio.h>
#include  <sys/types.h>

/* ----------------------------------------------------------------- */
/* FUNCTION  parse:                                                  */
/*    This function takes an input line and parse it into tokens.    */
/* It first replaces all white spaces with zeros until it hits a     */
/* non-white space character which indicates the beginning of an     */
/* argument.  It saves the address to argv[], and then skips all     */
/* non-white spaces which constitute the argument.                   */
/* ----------------------------------------------------------------- */

void  parse(char *line, char **argv)
{
     while (*line != '\0') {       /* if not the end of line ....... */
          while (*line == ' ' || *line == '\t' || *line == '\n')
               *line++ = '\0';     /* replace white spaces with 0    */
          *argv++ = line;          /* save the argument position     */
          while (*line != '\0' && *line != ' ' &&
                 *line != '\t' && *line != '\n')
               line++;             /* skip the argument until ...    */
     }
     *argv = '\0';                 /* mark the end of argument list  */
}

/* ----------------------------------------------------------------- */
/* FUNCTION execute:                                                 */
/*    This function receives a commend line argument list with the   */
/* first one being a file name followed by its arguments.  Then,     */
/* this function forks a child process to execute the command using  */
/* system call execvp().                                             */
/* ----------------------------------------------------------------- */
    
void  execute(char **argv)
{
     pid_t  pid;
     int    status;
    
     if ((pid = fork()) < 0) {     /* fork a child process           */
          printf("*** ERROR: forking child process failed\n");
          exit(1);
     }
     else if (pid == 0) {          /* for the child process:         */
          if (execvp(*argv, argv) < 0) {     /* execute the command  */
               printf("*** ERROR: exec failed\n");
               exit(1);
          }
     }
     else {                                  /* for the parent:      */
          while (wait(&status) != pid)       /* wait for completion  */
               ;
     }
}

/* ----------------------------------------------------------------- */
/*                  The main program starts here                     */
/* ----------------------------------------------------------------- */
    
void  main(void)
{
     char  line[1024];             /* the input line                 */
     char  *argv[64];              /* the command line argument      */
    
     while (1) {                   /* repeat until done ....         */
          printf("Shell -> ");     /*   display a prompt             */
          gets(line);              /*   read in the command line     */
          printf("\n");
          parse(line, argv);       /*   parse the line               */
          if (strcmp(argv[0], "exit") == 0)  /* is it an "exit"?     */
               exit(0);            /*   exit if it is                */
          execute(argv);           /* otherwise, execute the command */
     }
}

http://www.csl.mtu.edu/cs4411/www/NOTES/.../exec.html


Este mensaje fue modificado por última vez en: 02-28-2008 04:13 AM por p_eter.

02-28-2008 04:08 AM
Visita el website del usuario Encuentra todos los mensajes de este usuario Cita este mensaje en tu respuesta
Enviar Respuesta  Enviar Tema 

Ver la Versión para Impresión
Mandar este Tema a algún Amigo
Subscríbete a este Tema | Agrega este Tema a Tus Favoritos

Salto de Foro: