質問

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.

役に立ちましたか?

解決

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.

他のヒント

In this case, you may use popen().

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top