문제

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