Implementing shell in C and need help handling input/output redirection

前端 未结 3 862
名媛妹妹
名媛妹妹 2020-12-05 03:04

Round 2

After reading some of the answers, my revised code is:

int pid = fork();

if (pid == -1) {
    perror(\"fork\");
} else if (pid == 0) {   
         


        
3条回答
  •  时光说笑
    2020-12-05 03:49

    Here's what's happening. After you call fork() there are two processes executing that are duplicates of the original process. The difference is in the return value of fork() which is stored in pid.

    Then both processes (the shell and the child) redirect their stdin and stdout to the same files. I think you were trying to save the previous fd in current_out, but as Seth Robertson points out, this doesn't currently work, since the wrong file descriptor is being saved. The parent also restores its stdout, but not stdin.

    You could fix this bug, but you can do better. You don't actually have to redirect parent's output, just the child's. So simply check pid first. Then there is also no need to restore any file descriptors.

提交回复
热议问题