Why do you duplicate filedescriptor and never use it?

Here's the part:

extern fin;
char line[64];

if (argc<2 || ttyn(0)!='x') {
        write(1, "goto error\n", 11);
        seek(0, 0, 2);
        return;
}
seek(0, 0, 0);
fin = dup(0);

      

Note that throughout the code, the "fin" appears only in the part above. So why would you need to duplicate the std input (which is a file / script in this case), store it in a fin, and never use it?

You can find all the code here http://v6shell.org/history/goto.c with the syntax-highlighting here http://pastebin.com/uAvANLdR

PS. This is K & RC. The dup command used is described here: http://man.cat-v.org/unix-6th/2/dup

UPDATE: I found out that this is really needed for the getchar command. See http://man.cat-v.org/unix-6th/3/getchar

But I still don't understand why you need it. Can anyone tell me now?

+3


source to share


2 answers


If you look at the man page getchar (3)

http://man.cat-v.org/unix-6th/3/getchar

there is this little block:

Associated with this subroutine is an external variable called fin, which is a structure containing a buffer, such as described in section getc (III).

So if we take a closer look at getc (3)

http://man.cat-v.org/unix-6th/3/getc



we see that:

struct buf {
  int fildes;     /* File descriptor    */
  int nleft;      /* Chars left in buffer */
  char *nextp;    /* Ptr to next character */
  char buff[512]; /* The buffer */
};

      

The code in goto.c now makes hacks by telling the compiler that "fin" is int. Actually "fin" is of type struct buf, but as "int filedes"; is the first member that actually executes the code:

extern struct buf fin;

...

seek(0, 0, 0);
fin.fildes = dup(0);

      

As I said, this is a hackish solution, but the code seems pretty old anyway with all these gotos.

+3


source


One of the reasons I might have thought is that if fd 0 (stdin) is the end of a read in pipe (2) and closes later (i.e. after calling execve (2)), then anyone trying write to this pipe will still be blocked and will not receive a SIGPIPE signal.



+1


source







All Articles