0

I'm trying to shove some text files through a pipe that has been dup'd over sort's stdin. It works, but it does not terminate naturally(Interestingly,pressing the "enter" button seems to do it).

//child
if(rc == 0)
{
    alarm(60);
    close(stdin_pipe_fds[1]);

    close(0);
    dup(stdin_pipe_fds[0]);
    close(stdin_pipe_fds[0]);
    execve("/usr/bin/sort", argv, NULL);
    exit(0);
}

//Parent
if(rc >0)
{
    alarm(60);
    close(stdin_pipe_fds[0]);
    close(stdout_pipe_fds[1]);
    close(stderr_pipe_fds[1]);
    while(fscanf(coolFile, "%1023s", newWord) ==1)
    {
        if(strcmp(newWord, "foobar") != 0)
        {
            write(stdin_pipe_fds[1], newWord, (strlen(newWord)+1));
        }
    }
    if(argc == 2)
    {
        write(stdin_pipe, argc[2], 2);
    }
    if(argc == 3)
    {
        write(stdin_pipe, argc[3], 2);
    }
}

}

Any ideas?

1 Answers1

0

Here's an easier way to show the same effect:

$ cd /
$ ls -1 &                              # 1
[1] 58745
myuser@myhost / $ Applications         # 2
Library                                # 3
Network
System
Users
Volumes                                # 4
  1. A command is run in the background.
  2. You get your prompt back
  3. The output of the command starts overwriting the prompt
  4. The background command exits, but this does not cause the prompt to redraw. Since you don't see a prompt (it was trashed in step #2), you think the process is still running.
  5. When you press enter, the prompt is redrawn. Since you now have a visible prompt again, you incorrectly think that Enter caused the program to exit.

Instead, you could just have blindly typed echo "Hello World" and pressed enter, and you would have seen that the shell responds perfectly well. It's purely a cosmetic issue.

To fix this, you should:

  1. Have the parent wait() for the child, so that it does not exit before the child does.
  2. Make sure the parent closes the pipe entirely (before waiting). Previously, your parent exited immediately and closed the pipe. Since it will now wait for the child, you have to close the pipe manually to avoid a deadlock where the parent waits for the child to exit, while the child waits for the parent to continue or end input.
that other guy
  • 116,971
  • 11
  • 170
  • 194