File: port_read.c

package info (click to toggle)
cti-ifhp 2.1.8-2
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 932 kB
  • ctags: 845
  • sloc: ansic: 6,036; sh: 1,524; makefile: 318
file content (85 lines) | stat: -rw-r--r-- 2,251 bytes parent folder | download
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**************************************************************************
 * LPRng IFHP Filter
 * Copyright 1994-1997 Patrick Powell, San Diego, CA <papowell@sdsu.edu>
 *
 * Based on the CTI printer filters.
 *  See COPYRIGHT for details.
 *
 * $Id: port_read.c,v 2.2 1997/01/21 04:07:10 papowell Exp $
 */

#include "portable.h"
#include "common.h"
#include "hp4.h"


/*
 * Read a line from a descriptor with timeout.
 *  Read the line looking for '\r', `\n` or '\014'
 * (FormFeed is the terminator for all responses
 * from the HP LaserJet 4 printers).  We store the line in the buffer,
 * then follow it with a null (the same as fgets(3)).
 * We return the number of characters up to, but not including,
 * the null (the same as strlen(3)).
 * return:
 *  n > 0 - number of characters read
 *  n = 0 - timeout, no chars read
 *  n < 0 - EOF
 */

int port_readline(fd, ptr, maxlen, timec )
int    fd;
char   *ptr;
int    maxlen;
int    timec;
{
    int                      n, doread, rc, err;
    struct timeval           timeout;
    fd_set                   readfds;

	log(4,"port_readline: fd %d, maxlen %d, timeout %d", fd, maxlen, timec );

	ptr[0] = 0;
	n = doread = rc = 0;
    do {
		doread = rc = 0;
		FD_ZERO(&readfds);
		FD_SET( fd, &readfds);
		memset(&timeout, 0, sizeof(timeout) );
		if( timec == 0 ){
			timeout.tv_sec = 1;
		} else if( timec > 0 ){
			timeout.tv_sec = timec;
		} else {
			timeout.tv_sec = 1000000;	/* whacking great number */
		}
		if( n > 0 ){
			timeout.tv_sec = 1;
		}
		doread = select(fd+1, &readfds,(fd_set *)0,(fd_set *)0, &timeout);
		err = errno;
		log(4,"port_readline: select returned %d", doread );
		if( doread > 0 ){
			rc = read(fd, &ptr[n], maxlen - n );
			err = errno;
			log(8,"port_readline: read returned %d", rc );
			if( rc > 0 ) n += rc;
			ptr[n] = 0;
			if( strpbrk( ptr, "\014\n\r" ) ){
				break;
			}
		}
    } while( doread > 0 && rc > 0 && n < maxlen );
	log(4,"port_readline: read %d, '%s'", n, ptr );
	/* we we read something, then we return the amount */
	/* if we have a timeout, we return 0 */
	/* if we have an error, we return 0 */
	if( n == 0 ){
		if( doread == 0 ){
			n = 0;	/* timeout */
		} else {
			n = -1;	/* error during read or select */
		} 
	}
    return(n);
}