wangzhengquan
2020-12-22 26ed48c4e616014ee760fd13d13dbdc8539c34e3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*************************************************************************\
*                  Copyright (C) Michael Kerrisk, 2019.                   *
*                                                                         *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU General Public License as published by the   *
* Free Software Foundation, either version 3 or (at your option) any      *
* later version. This program is distributed without any warranty.  See   *
* the file COPYING.gpl-v3 for details.                                    *
\*************************************************************************/
 
/* Listing 59-5 */
 
/* is_seqnum.h
 
   Header file for is_seqnum_sv.c and is_seqnum_cl.c.
*/
#include <netinet/in.h>
#include <sys/socket.h>
#include <signal.h>
#include "usg_common.h"
 
#define PORT_NUM "50000"        /* Port number for server */
 
#define INT_LEN 30              /* Size of string able to hold largest
                                   integer (including terminating '\n') */
 
ssize_t
readLine(int fd, void *buffer, size_t n)
{
    ssize_t numRead;                    /* # of bytes fetched by last read() */
    size_t totRead;                     /* Total bytes read so far */
    char *buf;
    char ch;
 
    if (n <= 0 || buffer == NULL) {
        errno = EINVAL;
        return -1;
    }
 
    buf = (char *)buffer;                       /* No pointer arithmetic on "void *" */
 
    totRead = 0;
    for (;;) {
        numRead = read(fd, &ch, 1);
 
        if (numRead == -1) {
            if (errno == EINTR)         /* Interrupted --> restart read() */
                continue;
            else
                return -1;              /* Some other error */
 
        } else if (numRead == 0) {      /* EOF */
            if (totRead == 0)           /* No bytes read; return 0 */
                return 0;
            else                        /* Some bytes read; add '\0' */
                break;
 
        } else {                        /* 'numRead' must be 1 if we get here */
            if (totRead < n - 1) {      /* Discard > (n - 1) bytes */
                totRead++;
                *buf++ = ch;
            }
 
            if (ch == '\n')
                break;
        }
    }
 
    *buf = '\0';
    return totRead;
}