tags:

views:

99

answers:

3

Hello guys,

Currently, I'm implementing a simple shell in C language as my term project. I used fork and exec to execute the commands. However, some commands must be executed internally (fork and exec aren't allowed). Where can I find the source code for the shell commands?

+1  A: 

Depends on which shell you want:

bash? zsh? csh?

I'd go with something smaller like the busybox shell: http://busybox.net/downloads/

Ivan Kruchkoff
+1  A: 

It depends on the shell command. For commands like cd, all you end up doing is calling chdir(2).

But for things like shell variables (i.e. bash's var=value), the details will greatly depend on the internals of your implementation.

R Samuel Klatchko
+1  A: 

Take a ganders at Linux Application Development by Michael K Johnson and Erik W. Troan

In my Edition (2nd) you develop a simple shell (ladsh) as part of some examples (in 10.7) in pipes and process handling. A great educational resource.

Proved very useful for me.

A snippet:

struct childProgram {
    pid_t pid;              /* 0 if exited */
    char ** argv;           /* program name and arguments */
};

struct job {
    int jobId;              /* job number */
    int numProgs;           /* total number of programs in job */
    int runningProgs;       /* number of programs running */
    char * text;            /* name of job */
    char * cmdBuf;          /* buffer various argv's point into */
    pid_t pgrp;             /* process group ID for the job */
    struct childProgram * progs; /* array of programs in job */
    struct job * next;      /* to track background commands */
};

void freeJob(struct job * cmd) {
    int i;

    for (i = 0; i < cmd->numProgs; i++) {
        free(cmd->progs[i].argv);
    }
    free(cmd->progs);
    if (cmd->text) free(cmd->text);
    free(cmd->cmdBuf);
}

You can find the full source here under ladsh1.c, ladsh2.c and so on.

Aiden Bell