oopbase
oopbase

Reputation: 11385

Implementing a pipe in C?

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.

Upvotes: 1

Views: 166

Answers (2)

unwind
unwind

Reputation: 399723

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.

Upvotes: 1

TieDad
TieDad

Reputation: 9889

In this case, you may use popen().

Upvotes: 0

Related Questions