Question

I am trying to implement a simple shell. I fork processes this way:

void forkProcess(char* cmd[]) {
    pid_t pid;
    char programPath[BUFFERLENGTH] = "/bin/";
    strcat(programPath, cmd[0]);
    int exitStatus;
    pid = fork();
    switch (pid) {
    case -1:
        printf("Fork failed; pid == -1\n");
        break;
    case 0:
        execv(programPath, cmd);
        exit(0);
        break;
    default:
        waitpid(pid, &exitStatus, 0);
        //printf("Exitstatus = %d\n", WEXITSTATUS(exitStatus));
        break;
    }
}

Now the cmd parameter might contain a pipe, e.g.:

"ls" "-l" "|" "grep" "whatever" "(char*)NULL";

So how can I implement the pipe functionality? I know there are functions like pipe() and dup(), but I don't know how to use them in this context.

Thank you for any suggestions.

Was it helpful?

Solution

You must fully parse your command line before fork()ing to start the child.

If a pipe operator is being used, you must set up the pipe before calling fork(), so it is inherited.

In general you must also use close() and often dup() to make the pipe replace the forked process' stdin.

Continue reading up on these functions to "get" the big picture, or get a book which covers Unix I/O.

OTHER TIPS

In this case, you may use popen().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top