Communication. Serial port programming

Size: px
Start display at page:

Download "Communication. Serial port programming"

Transcription

1 Applied mechatronics Communication. Serial port programming Sven Gestegård Robertz Department of Computer Science, Lund University 2017

2 Outline 1 Introduction 2 Terminal I/O programming (in C) Raw I/O Structured I/O 3 Serial port programming Serial port configuration Serial port I/O Conclusion 4 Summary 5 Byte order Communication. Serial port programming 2/1

3 (Computer) mechatronics Controlling the physical world from a computer Sensors Actuators Communication with the user (operator) with other equipment Design systems for debugging Introduction Communication. Serial port programming 3/38

4 The lab project Building and programming a small servo system Building from PC towards embedded system Communication (serial port) Interface hardware Host (PC) programming Embedded system Building a simple microcontroller card Programming it Sensors and actuators The system depends on communication between PC and microcontroller Introduction Communication. Serial port programming 4/38

5 Communication between host and embedded system During operation Operator communication Mode changes, start/stop Implementing a feedback loop Reading process values Setting setpoints Setting parameters Make it possible to tune controllers during operation Less hard-coded parameters, less reprogramming, faster development cycle During development Monitoring the state of the program Printing or logging process values Facilitates debugging Introduction Communication. Serial port programming 5/38

6 A typical protocol Host to embedded system control word: mode changes data: reference (set-point) values Embedded system to host status word: current mode of operation, warnings and faults data: process values (feedback) Introduction Communication. Serial port programming 6/38

7 A typical protocol, simple example Message frames Master telegram: master (PC) slave (embedded system) Control word Position setpoint Velocity feedforward Slave telegram: slave master Status word Position feedback Velocity feedback Mode of operation controlled by control and status words Data format may depend on mode of operation Introduction Communication. Serial port programming 7/38

8 A typical protocol example (CANopen DS 402) Control word Status word Bit Name Bit Name 0 Switch on 8 Pause/halt 1 Disable voltage 9 Reserved 2 Quick stop 10 Reserved 3 Enable Operation 11 Ack. error 4 Op. mode specific 12 Reset position 5 Op. mode specific 13 Manufacturer specific 6 Op. mode specific 14 Manufacturer specific 7 Reset fault 15 Manufacturer specific Bit Name Bit Name 0 Ready to switch on 8 Reserved 1 Switched on 9 Remote 2 Operation enable 10 Target reached 3 Fault 11 Internal limit active 4 Disable voltage 12 Op. mode specific 5 Quick stop 13 Op. mode specific 6 Switch on disabled 14 Manufacturer specific 7 Warning 15 Manufacturer specific Introduction Communication. Serial port programming 8/38

9 Design decisions Trade-off communication efficiency vs. complexity of decoding messages A few large, complex or many small telegram types What data to send? Data types, sizes, ranges, and scaling Reserve space for future additions Byte order for >8 bit data types Introduction Communication. Serial port programming 9/38

10 Terminal Input/Output The fundamental concepts file descriptor - low level access open(), close() (more on these later) read(), write() Stream (FILE*) - structured access fdopen(), fclose() fprintf(), fgetc(), fgets() Tips: use fprintf() for output, but read() for input. or fgetc() for reading a single character See the serial port lab memo for details Terminal I/O programming (in C) Communication. Serial port programming 10/38

11 read() ssize_t read(int fd, void *buf, size_t count); Reads up to count characters from a file descriptor Returns on success: the number of characters read zero on end-of-file a negative value on error Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 11/38

12 Reading a single char with read() # include <stdio.h> # include <unistd.h> int main () { int run =1; } while ( run ){ ssize_t res ; char c; res = read ( STDIN_FILENO, &c, 1); if(res > 0 ) { printf (" Read : %c\n", c); } else { run = 0; } } return 0; Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 12/38

13 Reading a string with read() # include <stdio.h> # include <unistd.h> # define SIZE 10 int main () { int run =1; } while ( run ){ char c[ SIZE +1]; // +1: space for terminating null ssize_t res = read ( STDIN_FILENO, c, SIZE ); if(res > 0 ) { c[ res ] = \0 ; // add terminating null printf (" Read : %s\n", c); } else { run = 0; } } return 0; Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 13/38

14 Reading all input with read() Check return value and increment position # define SIZE 30 int main () { int run =1; char c[ SIZE +1]; size_t pos = 0; while ( run && pos < SIZE ){ ssize_t res = read ( STDIN_FILENO, c+pos, SIZE - pos ); if( res > 0 ) { // if more chars to read pos += res ; // increment pos } else { run = 0; } } c[ pos ] = \0 ; // add terminating null printf (" Buffer after read : %s\n", c); return 0; } Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 14/38

15 Raw access, writing with write() # include <sys / types.h> # include <string.h> # define BUFSIZE char buf [ BUFSIZE ]; size_t nbytes ; ssize_t bytes_written ; int fd;... strncpy ( buf, " This is a test \n", BUFSIZE ); nbytes = strnlen ( buf, BUFSIZE ); bytes_written = write (fd, buf, nbytes );... Terminal I/O programming (in C) : Raw I/O Communication. Serial port programming 15/38

16 Structured I/O Opening and closing streams FILE *fopen(const char *path, const char *mode); FILE *fdopen(int fd, const char *mode); where mode is (r)ead, (w)rite or (a)ppend. For read/write use r+, w+, or a+. # include < stdio.h> # include < errno.h> int fd;... FILE *f = fdopen (fd, "r"); if (!f){ perror (" fdopen "); } int fclose(file *fp); if( fclose (f )){ perror (" fclose "); } Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 16/38

17 Reading a single char from a stream: fgetc() int fgetc(file *stream); Reads one character from a stream Returns an unsigned char cast to int or the constant EOF (End-of-file) Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 17/38

18 Example: fgetc() # include <stdio.h> int main () { int res ; int run =1; } while ( run ){ res = fgetc ( stdin ); if( res!= EOF ) { char c = res ; printf (" Read : %c\n", c); } else { run = 0; } } return 0; Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 18/38

19 Read a C-string from a stream: fgets() char *fgets(char *s, int size, FILE *stream); Reads up to size 1 characters from a stream until a newline of EOF Adds a terminating null byte If a newline is read, it is stored into the buffer Returns s on success, or NULL on error of if no characters were read Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 19/38

20 More structured I/O Reading C strings: char *fgets(char *s, int size, FILE *stream); Example: char buf [ BUFSIZE ]; // BUFSIZE -1 chars + terminating null int fd;... FILE *f = fdopen (fd, "r"); if (! f){ // handle error or return error code...} char * res = fgets ( buf, BUFSIZE, f); if(res ) { printf (" input (%p): %s\n", res, buf ); } else { printf (" fgets returned NULL \n"); } Formatted values: int fprintf(file *stream, const char *format,...); int fscanf(file *stream, const char *format,...); Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 20/38

21 printf() format conversions character argument type; convert to d, i signed decimal notation x unsigned hexadecimal notation (w/o leading 0x) u unsigned decimal notation c single character (converted to char) f double in decimal notation [-]mmm.dddd s string (char *) the conversion characters may be preceeded with arguments for minimum width and/or precision. E.g., %4.2f : min 4 chars wide, 2 decimal positions %.8x : print (at least) 8 digits, padding with leading zeroes... and much more, consult a language reference Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 21/38

22 snprintf() example int snprintf(char *buf, size_t n, const char *format,...); Similar functionality to StringBuilder in Java Writes (at most) n characters (incl. terminating null) to buf. The return value is the number of chars in the resulting formatted string. If the return value is larger than n, the output was truncated. Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 22/38

23 snprintf() example # define BUFSZ 80 int main () { char buf [ BUFSZ ]; int x = 17; float f = 4.2; } snprintf ( buf, BUFSZ, " adding %d and %f equals %f", x, f, x+f) ; printf (" buf : %s\n", buf ); Terminal I/O programming (in C) : Structured I/O Communication. Serial port programming 23/38

24 Serial port setup Open the port Set communication parameters Data rate ( baud rate ): bits per second Data bits: bits per character (normally 7 or 8) Parity: (odd/even/none) Stop bits Flow control Close the port Serial port programming : Serial port configuration Communication. Serial port programming 24/38

25 Opening and closing the device int open(const char *path, int flags) returns a file descriptor path is the device name (e.g., /dev/ttys0) flags is a bitwise-inclusive OR of flags, including exactly one of O_RDONLY O_WRONLY O_RDWR E.g., int fd = open(port, O_RDWR O_NOCTTY O_NDELAY); Open for reading and writing The port is not the controlling terminal for the program Open non-blocking. Also on some systems: ignore the DCD ("carrier detect") line (On most systems, DCD is ignored anyway, so blocking is fine if you want that.) int close(int fd) closes the file descriptor, freeing the underlying resource returns zero on success Serial port programming : Serial port configuration Communication. Serial port programming 25/38

26 Opening the port Error handling const char * device = "/ dev / ttys0 "; int fd; fd = open ( device, O_RDWR O_NOCTTY ); if (fd < 0) { perror ( device ); exit ( -1); } The standard function void perror(const char *s) prints a system error message (include <errno.h>) Serial port programming : Serial port configuration Communication. Serial port programming 26/38

27 Port configuration Serial port configuration is fairly low-level read a struct with flags and parameters change the struct write back the updated struct s t r u c t t e r m i o s o p t i o n s ; // a l l o c a t e s t r u c t t c g e t a t t r ( fd, &o p t i o n s ) ; // Get o p t i o n s f o r t h e p o r t c f s e t i s p e e d (& o p t i o n s, B2400 ) ; // Set t h e baud r a t e s to 2400 c f s e t o s p e e d (& o p t i o n s, B2400 ) ; o p t i o n s. c _ c f l a g = (CLOCAL CREAD ) ; // Enable t h e r e c e i v e r and // i g n o r e modem c o n t r o l l i n e s / add o t h e r c o n f i g u r a t i o n ( e. g., n e x t s l i d e ) h e r e b e f o r e w r i t i n g back o p t i o n s / t c s e t a t t r ( fd, TCSANOW, &o p t i o n s ) ; // Write new o p t i o n s Serial port programming : Serial port configuration Communication. Serial port programming 27/38

28 Remarks CREAD: Enable receiver CLOCAL: Ignore modem control lines (i.e., CD). If CLOCAL is off, open() will block until the carrier detect signal is asserted (electrically), unless the flag O_NONBLOCK is set. Note that or (as in flags = a b) means and (as in set (the bits set in) a and b in flags). Serial port programming : Serial port configuration Communication. Serial port programming 28/38

29 Configuring the port Control options: Bnnnnn : bit rate CS8 : character size PARENB : enable parity bit CSTOPB : stop bits (2 stop bits if set ) CRTSCTS : output hardware flow control ( only used if the cable has all necessary lines. ) CREAD : enable receiver CLOCAL : local connection, no modem or job contol Serial port programming : Serial port configuration Communication. Serial port programming 29/38

30 Configuring the port struct termios options ; cfsetispeed (& options, B1200 ); cfsetospeed (& options, B1200 ); options. c_cflag = CLOCAL CREAD ; options. c_cflag &= ~ CSIZE ; options. c_cflag &= ~ PARENB ; options. c_cflag &= ~ CSTOPB ; options. c_cflag = CS8 ; // 8N1 options. c_cflag &= ~ CRTSCTS ; // No CTS / RTS tcsetattr (fd, TCSANOW, & options ); Serial port programming : Serial port configuration Communication. Serial port programming 30/38

31 Configuring the port Some local options: ISIG : enable job control signals ( INTR, SUSP, QUIT,...) ICANON : Everything is stored into a buffer, and can be edited until a carriage return or line feed ECHO : Enable echoing of input characters Serial port programming : Serial port configuration Communication. Serial port programming 31/38

32 Configuring the port Some input and output options: ICRNL : map CR to NL ( otherwise a CR input on the other computer may not terminate input ) IXON : Enable software flow control ( outgoing ) IXOFF : Enable software flow control ( incoming ) INPCK : Enable parity check IGNPAR : Ignore parity errors PARMRK : Mark parity errors ISTRIP : Strip parity bits ONLCR : Map NL to CR NL in output. Serial port programming : Serial port configuration Communication. Serial port programming 32/38

33 Interfaces to I/O operations raw access using file descriptors ssize_t read (int fd, void * buf, size_t nbyte ); ssize_t write (int fd, const void * buf, size_t nbyte ); structured access using streams FILE * fdopen ( int fd, const char * mode ) ; int fclose( FILE *stream ); int fgetc ( FILE * stream ); char * fgets ( char *s, int size, FILE * stream ); int fprintf(file *stream, const char *format,...); Serial port programming : Serial port I/O Communication. Serial port programming 33/38

34 Conclusion There is a self-study programming lab on the serial port (soon) on the web page Hints: Use the raw access functions for simple cases Don t use canonical mode unless reading linewise Use fprintf for more advanced output Avoid using fscanf Serial port programming : Conclusion Communication. Serial port programming 34/38

35 Communication Summary during development and during operation easier debugging less hard-coded parameters less reprogramming required in the final lab project Design a simple protocol Don t be alarmed by the serial port programming Summary Communication. Serial port programming 35/38

36 Questions? Summary Communication. Serial port programming 36/38

37 Byte order (Endianness) The serial link sends a series of bytes (characters) For data types larger than 8 bits is the most significant byte sent first (big endian) or last (little endian) Byte order (in memory) is CPU specific Example: 1000 as a 16 bit integer (== 0x3E8) Big endian: 0x03, 0xE8 ( network, IP, Java) Little endian: 0xE8, 0x03 (CANopen, Intel) Conversion is done by mask & shift. Be careful with sign extension (use unsigned in C). The same applies to values in memory Byte order Communication. Serial port programming 37/38

38 Example: Little endian memory In a byte-addressed memory, byte order must be defined for larger values First byte means lowest address Example: *a = 0x0A0B0C0D; Byte order Communication. Serial port programming 38/38

39 Flow Control / Handshaking Flow control Avoiding buffer overflow Fast communication Small buffers Receiver can pause communication if it cannot keep up with the data flow Hardware signals Signalling protocol Handshaking to establish a connection Agreement on data rates, packet type numbers, sequence numbers, etc. (e.g., SYN-ACK) Flow control/handshaking Communication. Serial port programming 39/38

40 Flow Control / Handshaking (2) DTR/DSR Data Terminal Ready / Data Set Ready Used for startup (typically: connection established over a modem line DSR Can be jumpered for direct connections RTS/CTS: Hardware flow control Request To Send: Terminal has data to send Clear To Send: Receiver ready to receive XON/XOFF: Software flow control In band signalling, bad for binary data Flow control/handshaking Communication. Serial port programming 40/38

Socket programming in C

Socket programming in C Socket programming in C Sven Gestegård Robertz September 2017 Abstract A socket is an endpoint of a communication channel or connection, and can be either local or over the network.

More information

Programming refresher and intro to C programming

Programming refresher and intro to C programming Applied mechatronics Programming refresher and intro to C programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2018 Outline 1 C programming intro 2

More information

File IO and command line input CSE 2451

File IO and command line input CSE 2451 File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to

More information

Experiment Number: 02. Title: PC-to-PC communication through RS-232 port

Experiment Number: 02. Title: PC-to-PC communication through RS-232 port R (2) N (5) Oral (3) Total (10) Dated Sign Experiment Number: 02 Title: PC-to-PC communication through RS-232 port OBJECTIVES: 1. To learn to perform PC-to-PC communication using the RS-232 port 2. To

More information

UNIX System Programming

UNIX System Programming File I/O 경희대학교컴퓨터공학과 조진성 UNIX System Programming File in UNIX n Unified interface for all I/Os in UNIX ü Regular(normal) files in file system ü Special files for devices terminal, keyboard, mouse, tape,

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 15: Unix interface: low-level interface Cristina Nita-Rotaru Lecture 15/Fall 2013 1 Streams Recap Higher-level interface, layered on top of the primitive file descriptor

More information

File Descriptors and Piping

File Descriptors and Piping File Descriptors and Piping CSC209: Software Tools and Systems Programming Furkan Alaca & Paul Vrbik University of Toronto Mississauga https://mcs.utm.utoronto.ca/~209/ Week 8 Today s topics File Descriptors

More information

CSE 410: Systems Programming

CSE 410: Systems Programming CSE 410: Systems Programming Input and Output Ethan Blanton Department of Computer Science and Engineering University at Buffalo I/O Kernel Services We have seen some text I/O using the C Standard Library.

More information

Operating System Labs. Yuanbin Wu

Operating System Labs. Yuanbin Wu Operating System Labs Yuanbin Wu cs@ecnu Annoucement Next Monday (28 Sept): We will have a lecture @ 4-302, 15:00-16:30 DON'T GO TO THE LABORATORY BUILDING! TA email update: ecnucchuang@163.com ecnucchuang@126.com

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight Exercise 7 due Monday (out later today) POSIX Portable Operating System Interface Family of standards specified by the

More information

HE-GE Linux USB Driver - User Guide. 1vv r2 03/25/2013

HE-GE Linux USB Driver - User Guide. 1vv r2 03/25/2013 Disclaimer SPECIFICATIONS SUBJECT TO CHANGE WITHOUT NOTICE Notice While reasonable efforts have been made to assure the accuracy of this document, Telit assumes no liability resulting from any inaccuracies

More information

Outline. OS Interface to Devices. System Input/Output. CSCI 4061 Introduction to Operating Systems. System I/O and Files. Instructor: Abhishek Chandra

Outline. OS Interface to Devices. System Input/Output. CSCI 4061 Introduction to Operating Systems. System I/O and Files. Instructor: Abhishek Chandra Outline CSCI 6 Introduction to Operating Systems System I/O and Files File I/O operations File Descriptors and redirection Pipes and FIFOs Instructor: Abhishek Chandra 2 System Input/Output Hardware devices:

More information

More on C programming

More on C programming Applied mechatronics More on C programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2017 Outline 1 Pointers and structs 2 On number representation Hexadecimal

More information

Advanced C Programming Topics

Advanced C Programming Topics Introductory Medical Device Prototyping Advanced C Programming Topics, http://saliterman.umn.edu/ Department of Biomedical Engineering, University of Minnesota Operations on Bits 1. Recall there are 8

More information

Input / Output Functions

Input / Output Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain

More information

System Software Experiment 1 Lecture 7

System Software Experiment 1 Lecture 7 System Software Experiment 1 Lecture 7 spring 2018 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungyunkwan University http://csl.skku.edu SSE3032: System Software Experiment 1, Spring 2018

More information

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x; C Input/Output Before we discuss I/O in C, let's review how C++ I/O works. int i; double x; cin >> i; cin >> x; cout

More information

Standard File Pointers

Standard File Pointers 1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf

More information

Input/Output and the Operating Systems

Input/Output and the Operating Systems Input/Output and the Operating Systems Fall 2015 Jinkyu Jeong (jinkyu@skku.edu) 1 I/O Functions Formatted I/O printf( ) and scanf( ) fprintf( ) and fscanf( ) sprintf( ) and sscanf( ) int printf(const char*

More information

Goals of this Lecture

Goals of this Lecture I/O Management 1 Goals of this Lecture Help you to learn about: The Unix stream concept Standard C I/O functions Unix system-level functions for I/O How the standard C I/O functions use the Unix system-level

More information

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture! I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix

More information

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture! I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix

More information

Processes often need to communicate. CSCB09: Software Tools and Systems Programming. Solution: Pipes. Recall: I/O mechanisms in C

Processes often need to communicate. CSCB09: Software Tools and Systems Programming. Solution: Pipes. Recall: I/O mechanisms in C 2017-03-06 Processes often need to communicate CSCB09: Software Tools and Systems Programming E.g. consider a shell pipeline: ps wc l ps needs to send its output to wc E.g. the different worker processes

More information

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based Chapter 5, Standard I/O Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based #include FILE *f; Standard files (FILE *varname) variable: stdin File Number: STDIN_FILENO

More information

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre Programming in C Session 8 Seema Sirpal Delhi University Computer Centre File I/O & Command Line Arguments An important part of any program is the ability to communicate with the world external to it.

More information

Operating System Labs. Yuanbin Wu

Operating System Labs. Yuanbin Wu Operating System Labs Yuanbin Wu cs@ecnu Announcement Project 1 due 21:00, Oct. 8 Operating System Labs Introduction of I/O operations Project 1 Sorting Operating System Labs Manipulate I/O System call

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 13 si 14: Unix interface for working with files. Cristina Nita-Rotaru Lecture 13/Fall 2013 1 Working with Files (I/O) File system: specifies how the information is organized

More information

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL. Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data

More information

Operating systems. Lecture 7

Operating systems. Lecture 7 Operating systems. Lecture 7 Michał Goliński 2018-11-13 Introduction Recall Plan for today History of C/C++ Compiler on the command line Automating builds with make CPU protection rings system calls pointers

More information

File I/O. Preprocessor Macros

File I/O. Preprocessor Macros Computer Programming File I/O. Preprocessor Macros Marius Minea marius@cs.upt.ro 4 December 2017 Files and streams A file is a data resource on persistent storage (e.g. disk). File contents are typically

More information

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Systems Programming. 08. Standard I/O Library. Alexander Holupirek Systems Programming 08. Standard I/O Library Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz Summer Term 2008 Last lecture:

More information

Lab # 4. Files & Queues in C

Lab # 4. Files & Queues in C Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4010: Lab # 4 Files & Queues in C Eng. Haneen El-Masry October, 2013 2 FILE * Files in C For C File I/O you need

More information

QC Linux USB Driver - User Guide 1vv r7 04/11/2014

QC Linux USB Driver - User Guide 1vv r7 04/11/2014 QC Linux USB Driver - User Guide Disclaimer SPECIFICATIONS SUBJECT TO CHANGE WITHOUT NOTICE Notice While reasonable efforts have been made to assure the accuracy of this document, Telit assumes no liability

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight HW2 Due Thursday, July 19 th Midterm on Monday, July 23 th 10:50-11:50 in TBD (And regular exercises in between) POSIX

More information

UNIX Terminals. Terminology. Serial Ports. Serial connection. Terminal Types. Terminal Types

UNIX Terminals. Terminology. Serial Ports. Serial connection. Terminal Types. Terminal Types Terminology UNIX Terminals bps Bits per second, the rate at which data is transmitted baud The number of electrical state transitions that may be made in a period of time DTE Data Terminal Equipment your

More information

Standard C Library Functions

Standard C Library Functions Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Memory, Files and Bitoperations (yaseminb@kth.se) Overview Overview Lecture 11: Memory, Files and Bit operations Main function; reading and writing Bitwise Operations Lecture 11: Memory, Files

More information

Section 3: File I/O, JSON, Generics. Meghan Cowan

Section 3: File I/O, JSON, Generics. Meghan Cowan Section 3: File I/O, JSON, Generics Meghan Cowan POSIX Family of standards specified by the IEEE Maintains compatibility across variants of Unix-like OS Defines API and standards for basic I/O: file, terminal

More information

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing Chapter 14: File Processing Files and Streams C views each file simply as a sequential stream of bytes. It ends as if there is an end-of-file marker. The data structure FILE, defined in stdio.h, stores

More information

Embedded programming, AVR intro

Embedded programming, AVR intro Applied mechatronics, Lab project Embedded programming, AVR intro Sven Gestegård Robertz Department of Computer Science, Lund University 2017 Outline 1 Low-level programming Bitwise operators Masking and

More information

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System What Is Operating System? Operating Systems, System Calls, and Buffered I/O emacs gcc Browser DVD Player Operating System CS 217 1 Abstraction of hardware Virtualization Protection and security 2 Academic

More information

CMPSC 311- Introduction to Systems Programming Module: Input/Output

CMPSC 311- Introduction to Systems Programming Module: Input/Output CMPSC 311- Introduction to Systems Programming Module: Input/Output Professor Patrick McDaniel Fall 2014 Input/Out Input/output is the process of moving bytes into and out of the process space. terminal/keyboard

More information

UNIX System Calls. Sys Calls versus Library Func

UNIX System Calls. Sys Calls versus Library Func UNIX System Calls Entry points to the kernel Provide services to the processes One feature that cannot be changed Definitions are in C For most system calls a function with the same name exists in the

More information

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto For more information please consult Advanced Programming in the UNIX Environment, 3rd Edition, W. Richard Stevens and

More information

File I/O. Arash Rafiey. November 7, 2017

File I/O. Arash Rafiey. November 7, 2017 November 7, 2017 Files File is a place on disk where a group of related data is stored. Files File is a place on disk where a group of related data is stored. C provides various functions to handle files

More information

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017 Computer Security Robust and secure programming in C Marius Minea marius@cs.upt.ro 12 October 2017 In this lecture Write correct code minimizing risks with proper error handling avoiding security pitfalls

More information

CMSC 216 Introduction to Computer Systems Lecture 17 Process Control and System-Level I/O

CMSC 216 Introduction to Computer Systems Lecture 17 Process Control and System-Level I/O CMSC 216 Introduction to Computer Systems Lecture 17 Process Control and System-Level I/O Sections 8.2-8.5, Bryant and O'Hallaron PROCESS CONTROL (CONT.) CMSC 216 - Wood, Sussman, Herman, Plane 2 Signals

More information

C mini reference. 5 Binary numbers 12

C mini reference. 5 Binary numbers 12 C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char

More information

File Handling in C. EECS 2031 Fall October 27, 2014

File Handling in C. EECS 2031 Fall October 27, 2014 File Handling in C EECS 2031 Fall 2014 October 27, 2014 1 Reading from and writing to files in C l stdio.h contains several functions that allow us to read from and write to files l Their names typically

More information

File Access. FILE * fopen(const char *name, const char * mode);

File Access. FILE * fopen(const char *name, const char * mode); File Access, K&R 7.5 Dealing with named files is surprisingly similar to dealing with stdin and stdout. Start by declaring a "file pointer": FILE *fp; /* See Appendix B1.1, pg. 242 */ header

More information

UNIX input and output

UNIX input and output UNIX input and output Disk files In UNIX a disk file is a finite sequence of bytes, usually stored on some nonvolatile medium. Disk files have names, which are called paths. We won t discuss file naming

More information

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments File I/O Content Input Output Devices File access Function of File I/O Redirection Command-line arguments UNIX and C language C is a general-purpose, high-level language that was originally developed by

More information

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo I/O OPERATIONS UNIX Programming 2014 Fall by Euiseong Seo Files Files that contain a stream of bytes are called regular files Regular files can be any of followings ASCII text Data Executable code Shell

More information

Unix File and I/O. Outline. Storing Information. File Systems. (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu

Unix File and I/O. Outline. Storing Information. File Systems. (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu Outline Unix File and I/O (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu Basics of File Systems Directory and Unix File System: inode UNIX I/O System Calls: open, close, read, write, ioctl File Representations:

More information

Standard I/O in C, Computer System and programming in C

Standard I/O in C, Computer System and programming in C Standard I/O in C, Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files and Information 7. Environment

More information

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CSci 4061 Introduction to Operating Systems. Input/Output: High-level CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device

More information

PL-2303 specific usb-uart serial communications manager for QNX Neutrino

PL-2303 specific usb-uart serial communications manager for QNX Neutrino Driver - Description devu-prolific2303-speed PL-2303 specific usb-uart serial communications manager for QNX Neutrino You must be root to start this driver. Syntax: devu-prolific2303 [[options] [u devicenr

More information

Preview. Interprocess Communication with Pipe. Pipe from the Parent to the child Pipe from the child to the parent FIFO popen() with r Popen() with w

Preview. Interprocess Communication with Pipe. Pipe from the Parent to the child Pipe from the child to the parent FIFO popen() with r Popen() with w Preview Interprocess Communication with Pipe Pipe from the Parent to the child Pipe from the child to the parent FIFO popen() with r Popen() with w COCS 350 System Software, Fall 2015 1 Interprocess Communication

More information

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file. File Structures Physical Files and Logical Files Chap 2. Fundamental File Processing Operations Things you have to learn Physical files and logical files File processing operations: create, open, close,

More information

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) Topic 8: I/O Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) No C language primitives for I/O; all done via function

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics

More information

Stream Model of I/O. Basic I/O in C

Stream Model of I/O. Basic I/O in C Stream Model of I/O 1 A stream provides a connection between the process that initializes it and an object, such as a file, which may be viewed as a sequence of data. In the simplest view, a stream object

More information

25.2 Opening and Closing a File

25.2 Opening and Closing a File Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:

More information

Operating Systems. Lecture 06. System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line

Operating Systems. Lecture 06. System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line Operating Systems Lecture 06 System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line March 04, 2013 exec() Typically the exec system call is

More information

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo I/O OPERATIONS UNIX Programming 2014 Fall by Euiseong Seo Files Files that contain a stream of bytes are called regular files Regular files can be any of followings ASCII text Data Executable code Shell

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

Recitation 8: Tshlab + VM

Recitation 8: Tshlab + VM Recitation 8: Tshlab + VM Instructor: TAs 1 Outline Labs Signals IO Virtual Memory 2 TshLab and MallocLab TshLab due Tuesday MallocLab is released immediately after Start early Do the checkpoint first,

More information

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline. CMPE-013/L Outline File Processing File I/O Gabriel Hugh Elkaim Winter 2014 Files and Streams Open and Close Files Read and Write Sequential Files Read and Write Random Access Files Read and Write Random

More information

Course organization. Course introduction ( Week 1)

Course organization. Course introduction ( Week 1) Course organization Course introduction ( Week 1) Code editor: Emacs Part I: Introduction to C programming language (Week 2-9) Chapter 1: Overall Introduction (Week 1-3) Chapter 2: Types, operators and

More information

Process Management! Goals of this Lecture!

Process Management! Goals of this Lecture! Process Management! 1 Goals of this Lecture! Help you learn about:" Creating new processes" Programmatically redirecting stdin, stdout, and stderr" Unix system-level functions for I/O" The Unix stream

More information

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm)

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm) Final Test Duration 50 minutes Aids allowed: none Last Name: Student Number: First Name: Instructor: Reid Section: L5101 (6:10-7:00pm) Do not turn this page until you have received the signal to start.

More information

ECE551 Midterm Version 1

ECE551 Midterm Version 1 Name: ECE551 Midterm Version 1 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

CSE 351: The Hardware/Software Interface. Section 2 Integer representations, two s complement, and bitwise operators

CSE 351: The Hardware/Software Interface. Section 2 Integer representations, two s complement, and bitwise operators CSE 351: The Hardware/Software Interface Section 2 Integer representations, two s complement, and bitwise operators Integer representations In addition to decimal notation, it s important to be able to

More information

File and Console I/O. CS449 Spring 2016

File and Console I/O. CS449 Spring 2016 File and Console I/O CS449 Spring 2016 What is a Unix(or Linux) File? File: a resource for storing information [sic] based on some kind of durable storage (Wikipedia) Wider sense: In Unix, everything is

More information

Naked C Lecture 6. File Operations and System Calls

Naked C Lecture 6. File Operations and System Calls Naked C Lecture 6 File Operations and System Calls 20 August 2012 Libc and Linking Libc is the standard C library Provides most of the basic functionality that we've been using String functions, fork,

More information

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions. UNIT-V Unit-5 File Streams Formatted I/O Preprocessor Directives Printf Scanf A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage

More information

Terminal Modem Mice. Computer Center, CS, NCTU

Terminal Modem Mice. Computer Center, CS, NCTU Serial Devices Serial devices Terminal Modem Mice Computer Center, CS, NCTU 2 Serial standard (1) RS-232 standard on DB25 connector Electrical characteristics Meaning of each signal wire Ping assignment

More information

Computer Center, CS, NCTU. Serial devices. Terminal Modem Mice

Computer Center, CS, NCTU. Serial devices. Terminal Modem Mice Serial Devices Serial devices Terminal Modem Mice 2 Serial standard (1) RS-232 standard on DB25 connector Electrical characteristics Meaning of each signal wire Ping assignment DB25P (male) DB25S (female)

More information

CS 261 Fall Mike Lam, Professor. Structs and I/O

CS 261 Fall Mike Lam, Professor. Structs and I/O CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful

More information

CSC209H Lecture 7. Dan Zingaro. February 25, 2015

CSC209H Lecture 7. Dan Zingaro. February 25, 2015 CSC209H Lecture 7 Dan Zingaro February 25, 2015 Inter-process Communication (IPC) Remember that after a fork, the two processes are independent We re going to use pipes to let the processes communicate

More information

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University File I/O Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Unix Files A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O devices

More information

C Basics And Concepts Input And Output

C Basics And Concepts Input And Output C Basics And Concepts Input And Output Report Working group scientific computing Department of informatics Faculty of mathematics, informatics and natural sciences University of Hamburg Written by: Marcus

More information

Files. Eric McCreath

Files. Eric McCreath Files Eric McCreath 2 What is a file? Information used by a computer system may be stored on a variety of storage mediums (magnetic disks, magnetic tapes, optical disks, flash disks etc). However, as a

More information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am)

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am) Midterm Test Duration 50 minutes Aids allowed: none Last Name: Student Number: First Name: Instructor: Reid Section: L0101 (10:10-11:00am) Do not turn this page until you have received the signal to start.

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:

More information

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch. 1 Quick review of previous lecture Ch6 Structure Ch7 I/O EECS2031 Software Tools C - Structures, Unions, Enums & Typedef (K&R Ch.6) Structures Basics: Declaration and assignment Structures and functions

More information

Engineering program development 7. Edited by Péter Vass

Engineering program development 7. Edited by Péter Vass Engineering program development 7 Edited by Péter Vass Functions Function is a separate computational unit which has its own name (identifier). The objective of a function is solving a well-defined problem.

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 12: Memory, Files and Bitoperations (pronobis@kth.se) Overview Overview Lecture 12: Memory, Files and Bit operations Wrap Up Main function; reading and writing Bitwise Operations Wrap Up Lecture

More information

Preview. System Call. System Call. System Call. System Call. Library Functions 9/20/2018. System Call

Preview. System Call. System Call. System Call. System Call. Library Functions 9/20/2018. System Call Preview File Descriptors for a Process for Managing Files write read open close lseek A system call is a request for the operating system to do something on behalf of the user's program. The system calls

More information

Input and Output System Calls

Input and Output System Calls Chapter 2 Input and Output System Calls Internal UNIX System Calls & Libraries Using C --- 1011 OBJECTIVES Upon completion of this unit, you will be able to: Describe the characteristics of a file Open

More information

How do we define pointers? Memory allocation. Syntax. Notes. Pointers to variables. Pointers to structures. Pointers to functions. Notes.

How do we define pointers? Memory allocation. Syntax. Notes. Pointers to variables. Pointers to structures. Pointers to functions. Notes. , 1 / 33, Summer 2010 Department of Computer Science and Engineering York University Toronto June 15, 2010 Table of contents, 2 / 33 1 2 3 Exam, 4 / 33 You did well Standard input processing Testing Debugging

More information

System Programming. Standard Input/Output Library (Cont d)

System Programming. Standard Input/Output Library (Cont d) Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Binary I/O 2 3 4 5 Binary

More information

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection 1 Files 1.1 File functions Opening Files : The function fopen opens a file and returns a FILE pointer. FILE *fopen( const char * filename, const char * mode ); The allowed modes for fopen are as follows

More information

2009 S2 COMP File Operations

2009 S2 COMP File Operations 2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations

More information

SWEN-250 Personal SE. Introduction to C

SWEN-250 Personal SE. Introduction to C SWEN-250 Personal SE Introduction to C A Bit of History Developed in the early to mid 70s Dennis Ritchie as a systems programming language. Adopted by Ken Thompson to write Unix on a the PDP-11. At the

More information

File (1A) Young Won Lim 11/25/16

File (1A) Young Won Lim 11/25/16 File (1A) Copyright (c) 2010-2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version

More information

SYNOPSIS #include <termios.h> #include <unistd.h>

SYNOPSIS #include <termios.h> #include <unistd.h> NAME termios, tcgetattr, tcsetattr, tcsendbreak, tcdrain, tcflush, tcflow, cfmakeraw, cfgetospeed, cfgetispeed, cfsetispeed, cfsetospeed, cfsetspeed get and set terminal attributes, line control, get and

More information

CS 201. Files and I/O. Gerson Robboy Portland State University

CS 201. Files and I/O. Gerson Robboy Portland State University CS 201 Files and I/O Gerson Robboy Portland State University A Typical Hardware System CPU chip register file ALU system bus memory bus bus interface I/O bridge main memory USB controller graphics adapter

More information

File I/O, Project 1: List ADT. Bryce Boe 2013/07/02 CS24, Summer 2013 C

File I/O, Project 1: List ADT. Bryce Boe 2013/07/02 CS24, Summer 2013 C File I/O, Project 1: List ADT Bryce Boe 2013/07/02 CS24, Summer 2013 C Outline Memory Layout Review Pointers and Arrays Example File I/O Project 1 List ADT MEMORY LAYOUT REVIEW Simplified process s address

More information