Distributed Real-Time Control Systems. Lecture 24 Asynchronous Socket Communications

Size: px
Start display at page:

Download "Distributed Real-Time Control Systems. Lecture 24 Asynchronous Socket Communications"

Transcription

1 Distributed Real-Time Control Systems Lecture 24 Asynchronous Socket Communications with Boost ASIO 1

2 Boost Asynchronous I/O (ASIO) Boost::Asio allows implements a service for asynchronous I/O: boost::asio::io_service The service provides: A thread pool transparent to the user. Asyncronous operation starterswith user completion handlers. Important functions acceptor::async_accept socket::async_connect socket::async_receive_from socket::async_send_to socket::async_write socket::async_read resolver::async_resolve 2

3 Asynchronous UDP Server #include <string> #include <iostream> #include <boost/asio.hpp> #include <boost/array.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> using namespace boost::asio; using boost::asio::ip::udp; class udp_server { private: udp::socketsock_; udp::endpoint remote_ep_; boost::array<char, 1> recv_buffer_; void handle_receive(); void handle_send(shared_ptr<std::string> msg); void start_receive(); public: udp_server(io_service& io) : sock_(io, udp::endpoint(udp::v4(), 10000)) { start_receive(); ; void udp_server::start_receive() { sock_.async_receive_from( buffer(recv_buffer_), remote_ep_, boost::bind(&udp_server::handle_receive, this); void udp_server::handle_receive() { boost::shared_ptr<std::string> msg(new std::string( Hello")); sock_.async_send_to(buffer(*msg), remote_ep_, boost::bind(&udp_server::handle_send, this, msg); start_receive(); void udp_server::handle_send(shared_ptr<std::string> msg) { std::cout << "Sent: " << *msg << std::endl; int main() { io_service io; udp_server server(io); io.run(); 3

4 Notes on Asynchronous UDP Server Class udp_server encapsulatedsockets, endpoints, communication buffers and asynchronousoperationhandlers. To invoke class member functions as handlers to asynchronous operations, must use a functor (function object), that associates the member function to the associated object (via a pointer to the object). boost::bind(&udp_server::handle_receive, this); Functors can receive arguments: boost::bind(&udp_server::handle_send, this, msg); 4

5 More about boost::bind boost::bind is an object that encapsulates functions and arguments to be called in the future. bind(f, _2, _1)(x, y); // f(y, x) bind(g, _1, 9, _1)(x); // g(x, 9, x) bind(g, _3, _3, _3)(x, y, z); // g(z, z, z) bind(g, _1, _1, _1)(x, y, z); // g(x, x, x) 5

6 Communication Buffers Lifetime Management Because async_ functions return immediately, we must make sure the communication buffer still exists when the asynchronous operationexecutes. // very bad code... void on_read(const boost::system::error_code & err, std::size_t read_ bytes) {... void func() { char buff[512]; sock.async_receive(buffer(buff), on_read); A poor solution to the problem is to use global variables, but we can do better. 6

7 Raw Buffer Lifetime Management Create a buffer on the heap, pass it to the handler, and destroyitwhen the operationcompletes. void on_read(char * ptr, const boost::system::error_code & err, std::size_t read_bytes) { //do stuff delete[] ptr; //... char * buff = new char[512]; sock.async_receive(buffer(buff, 512), boost::bind(on_ read,buff,_1,_2) ); To pass the buffer to the handler, can use function object boost::bind. boost::bind(on_ read,buff,_1,_2) _1 and _2 correspond to the first and second arguments of an async_receive handler error_code and size_t, respectivelly. 7

8 Buffer Lifetime with Smart Pointers Using smart pointers, objectlifetimemanagement can be easier. class shared_buffer { boost::shared_array<char> buff; //like a shared pointer but for arrays int size; shared_buffer(size_t size) : buff(new char[size]), size(size) { //constructor auto asio_buff() const { return buffer(buff.get(), size); void on_read(shared_buffer sbuf, const boost::system::error_code & err, std::size_t read_bytes) { //the shared pointer assures sbuf still lives at this point // shared_buffer buff(512); sock.async_receive(buff.asio_buff(), boost::bind(on_ read, buff, _1, _2) ); 8

9 Buffer Lifetime Management with Shared this One can encapsulate data buffers and handlers on a helper class. Buffer lifetime can be managed by keeping the helper object alive by passinga shared pointer to the object itself(this) to the handler function. using namespace boost::asio; struct connection : boost::enable_shared_from_this<connection> { ip::tcp::socket sock_; char read_buffer_[1024]; connection(io_service service) : sock_(service) { void start(ip::tcp::endpoint ep) { sock_.async_connect(ep, boost::bind(&connection::on_connect, shared_from_this(), _1)); void on_connect(const boost::system::error_code & err) { // decide what to do with the connection, e.g. read sock_.async_read_some(buffer(read_buffer_), boost::bind(&connection::on_read, shared_from_this(), _1, _2)); void on_read(const boost::system::error_code & err, size_t bytes) { //can use read buffer safely ; // io_service service; ip::tcp::endpoint ep( ip::address::from_string(" "), 8001); connection::boost::shared_ptr<connection>( new connection {service )->start(ep); 9

10 Comments on Previous Slide Class enable_shared_from_this<t> defines two member functions called shared_from_this that return a shared_ptr<t> and shared_ptr<t const>, dependingon constness, to this. It also defines two member functions called weak_from_this that return a corresponding weak_ptr. Binding a shared pointerto the asynchronous operation handlers keeps the reference count positive, so the object cannot be destroyedbeforecompletion. 10

11 Asynchronous TCP Server #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/asio.hpp> using namespace boost::asio; using ip::tcp; class tcp_connection : public boost::enable_shared_from_this<tcp_connection> { private: tcp::socket sock_; std::string msg_; tcp_connection(io_service& io) : sock_(io) { void handle_write() {/*nothing important*/ public: ; typedef boost::shared_ptr<tcp_connection> pointer; static pointer create(io_service& io) { return pointer(new tcp_connection(io)); tcp::socket& socket() {return socket_; void start() { async_write(sock_,buffer( Hello World ), boost::bind(&tcp_connection::handle_write, shared_from_this())); class tcp_server { private: tcp::acceptor acceptor_; public: tcp_server(io_service& io) : acceptor_(io, tcp::endpoint(tcp::v4(), 10000)) { private: start_accept(); void start_accept() { tcp_connection::pointer new_con = tcp_connection::create(acceptor_.get_io_service()); acceptor_.async_accept(new_con->socket(), boost::bind(&tcp_server::handle_accept, this, new_con)); ; void handle_accept(tcp_connection::pointer new_con) { new_con->start(); start_accept(); int main() { io_service io; tcp_server server(io); io.run(); 11

12 Debugging Asynchronous Operations Boost.Asio allows for handler tracking, when the macro BOOST_ASIO_ENABLE_HANDLER_TRACKING is defined. Outputs messages along asynchronous <timestamp> <action> <description>. Try on async_tcp_echo_server.cpp: #define BOOST_ASIO_ENABLE_HANDLER_TRACKING #include<boost/asio.hpp> Note: The #define must be before the #include 12

13 Debug Information //Start *1 //server creates hnd 1 (async_accept) //Client >1 ec=system:0 //enter hnd *2 socket@0x23c52f0.async_receive //hnd 1 creates hndr *3 socket@0x7ffca28b3298.async_accept //hnd 1 creates hnd <85112 //exit hnd 1 //Client send >2 ec=system:0,bytes_transferred=5 //enter hnd *4 socket@0x23c52f0.async_send //hnd 2 creates hnd < //exit hnd 2 //Server write >4 ec=system:0,bytes_transferred=5 //enter hnd *5 socket@0x23c52f0.async_receive //hnd 4 creates hnd < //exit hnd 4 //Server close >5 ec=asio.misc:2,bytes_transferred=0 //enter hnd socket@0x23c52f0.close //hnd 5 action socket < //exit hnd 5 13

14 Asynchronous Reading STDIN // MODIFY class server IN ASYNC_TCP_ECHO_SERVER using boost::asio::ip::tcp; using boost::system::error_code class server{ boost::asio::io_service& io_service_; tcp::acceptor acceptor_; boost::asio::posix::stream_descriptor input_; boost::asio::streambuf input_buffer_; public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), private: input_(io_service, ::dup(stdin_fileno)), input_buffer_(1024), acceptor_(io_service, tcp::endpoint(tcp::v4(), port)) { start_accept(); start_read_input(); void start_accept() { session* new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind(&server::handle_accept, this, new_session, _1)); void start_read_input() { // Read a line of input entered by the user. boost::asio::async_read_until(input_, input_buffer_, '\n', boost::bind(&server::handle_read_input, this, _1, _2)); void handle_read_input( const error_code& error, std::size_t length){ std::cout << &input_buffer_ << std::endl; start_read_input(); void handle_accept(session* new_session, const error_code& error) { if (!error) { new_session->start(); else { delete new_session; start_accept(); ; int main(int argc, char* argv[]) { boost::asio::io_service io_service; server s(io_service, atoi(argv[1])); io_service.run(); 14

Distributed Real-Time Control Systems. Lecture 19 Asynchronous Communications

Distributed Real-Time Control Systems. Lecture 19 Asynchronous Communications Distributed Real-Time Control Systems Lecture 19 Asynchronous Communications 1 Synchronous vs Asyncronous I/O Synchronous: The process sending/receiving data executed the write/read operation and waits

More information

Distributed Real-Time Control Systems. Chapter 22 Asynchronous I/O The Boost ASIO Library

Distributed Real-Time Control Systems. Chapter 22 Asynchronous I/O The Boost ASIO Library Distributed Real-Time Control Systems Chapter 22 Asynchronous I/O The Boost ASIO Library 1 Synchronous vs Asyncronous I/O Synchronous (also called rendez-vous model) : The process sending/receiving data

More information

Distributed Real-Time Control Systems

Distributed Real-Time Control Systems Distributed Real-Time Control Systems Chapter 23 Additional C++ and Boost ASIO Features 1 Callable Objects 2 Function Objects Function objects (or Functors) are objects specifically designed to be used

More information

Distributed Real-Time Control Systems. Module 26 Sockets

Distributed Real-Time Control Systems. Module 26 Sockets Distributed Real-Time Control Systems Module 26 Sockets 1 Network Programming with Sockets Sockets are probably the most widely used objects in programming networked communications. What is a socket? To

More information

Distributed Real-Time Control Systems

Distributed Real-Time Control Systems Distributed Real-Time Control Systems Lecture 18 More on Boost ASIO Ethernet Communications Sockets in C++ 1 Boost Asio Communication Functions Boost Asio abstracts communication channels as streams. Streams

More information

Asynchronous I/O With boost.asio

Asynchronous I/O With boost.asio Asynchronous I/O With boost.asio Avishay Orpaz avishorp@gmail.com @avishorp https://github.com/avishorp SO, You want to make some I/O. SO, You want to make some I/O. That s pretty easy: //Create socket

More information

Distributed Real-Time Control Systems. Lecture 17 C++ Exceptions Synchronous I/O

Distributed Real-Time Control Systems. Lecture 17 C++ Exceptions Synchronous I/O Distributed Real-Time Control Systems Lecture 17 C++ Exceptions Synchronous I/O 1 Traditional Error Handling Well behaved code should notonlyfocus on operation under normal conditions but also under error

More information

Boost ASIO. Broadcasts and Multiple Interfaces Georg Hellack

Boost ASIO. Broadcasts and Multiple Interfaces Georg Hellack Boost ASIO Broadcasts and Multiple Interfaces Key Components of ASIO io_service interacts with operating system calls handlers non-copyable -> use shared_ptr I/O objects, e.g. tcp::socket, udp::socket

More information

Creating Boost.Asio extensions

Creating Boost.Asio extensions Creating Boost.Asio extensions Boris Schäling, May 2011, www.highscore.de How does Boost.Asio look like internally? What are I/O service objects, I/O services and I/O objects? How do I access platform-specific

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 13 -- smart pointers Steve Gribble Department of Computer Science & Engineering University of Washington Administrivia HW2 is due on Thursday! - check out the discussion board for a few

More information

PROGRAMMING IN C++ CVIČENÍ

PROGRAMMING IN C++ CVIČENÍ PROGRAMMING IN C++ CVIČENÍ INFORMACE Michal Brabec http://www.ksi.mff.cuni.cz/ http://www.ksi.mff.cuni.cz/~brabec/ brabec@ksi.mff.cuni.cz gmichal.brabec@gmail.com REQUIREMENTS FOR COURSE CREDIT Basic requirements

More information

Exceptions. CS162: Introduction to Computer Science II. Exceptions. Exceptions. Exceptions. Exceptions. Exceptions

Exceptions. CS162: Introduction to Computer Science II. Exceptions. Exceptions. Exceptions. Exceptions. Exceptions CS162: Introduction to Computer Science II A typical way to handle error conditions is through the return value. For example, suppose we create a loadfile() function that returns true if it loaded the

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Smart Pointers and Constness Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer

More information

Boost.Asio C++ Network Programming

Boost.Asio C++ Network Programming Boost.Asio C++ Network Programming Enhance your skills with practical examples for C++ network programming John Torjo BIRMINGHAM - MUMBAI Boost.Asio C++ Network Programming Copyright 2013 Packt Publishing

More information

Homework 4. Any questions?

Homework 4. Any questions? CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 14 -- smart pointers Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia Midterm Friday - Review in sections this week - Closed book; topic list

More information

Common Misunderstandings from Exam 1 Material

Common Misunderstandings from Exam 1 Material Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself

More information

Program template-smart-pointers-again.cc

Program template-smart-pointers-again.cc 1 // Illustrate the smart pointer approach using Templates 2 // George F. Riley, Georgia Tech, Spring 2012 3 // This is nearly identical to the earlier handout on smart pointers 4 // but uses a different

More information

Program template-smart-pointers.cc

Program template-smart-pointers.cc 1 // Illustrate the smart pointer approach using Templates 2 // George F. Riley, Georgia Tech, Spring 2012 3 4 #include 5 #include 6 7 using namespace std; 8 9 // The Ptr class contains

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

Assignment description: This is a C++ project. The comms class containing the

Assignment description: This is a C++ project. The comms class containing the Assignment description: This is a C++ project. The comms class containing the code that is common to both the client and server. The classes should contain the functionality required to establishing a

More information

C++ Modern and Lucid C++ for Professional Programmers

C++ Modern and Lucid C++ for Professional Programmers Informatik C++ Modern and Lucid C++ for Professional Programmers part 13 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2017 main(argc,argv) Arrays & Pointer passing arguments

More information

Programmazione. Prof. Marco Bertini

Programmazione. Prof. Marco Bertini Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Hello world : a review Some differences between C and C++ Let s review some differences between C and C++ looking

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example

More information

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

CMPS 105 Systems Programming. Prof. Darrell Long E2.371 + CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 7: The Environment of a UNIX process + Introduction + The main() fuction n int main(int argc, char* argv[]); n argc =

More information

Structuur van Computerprogramma s 2

Structuur van Computerprogramma s 2 Structuur van Computerprogramma s 2 dr. Dirk Deridder Dirk.Deridder@vub.ac.be http://soft.vub.ac.be/ Vrije Universiteit Brussel - Faculty of Science and Bio-Engineering Sciences - Computer Science Department

More information

libknx Generated by Doxygen Wed Aug :37:55

libknx Generated by Doxygen Wed Aug :37:55 libknx Generated by Doxygen 1.8.1.2 Wed Aug 7 2013 01:37:55 Contents 1 KNX interface library 1 2 Namespace Index 3 2.1 Namespace List............................................ 3 3 Class Index 5 3.1

More information

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy CSCI 334: Principles of Programming Languages Lecture 18: C/C++ Homework help session will be tomorrow from 7-9pm in Schow 030A instead of on Thursday. Instructor: Dan Barowy HW6 and HW7 solutions We only

More information

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

An Introduction to the C++ Network Library. Glyn Matthews Belgian C++ User Group

An Introduction to the C++ Network Library. Glyn Matthews Belgian C++ User Group An Introduction to the C++ Network Library Glyn Matthews Belgian C++ User Group INTRODUCTION NETWORK PROGRAMMING IN C++ C++ NETWORK LIBRARY (0.9.4) C++1Y THE FUTURE About me Glyn Matthews Software Engineer

More information

NETWORK PROGRAMMING. Instructor: Junaid Tariq, Lecturer, Department of Computer Science

NETWORK PROGRAMMING. Instructor: Junaid Tariq, Lecturer, Department of Computer Science NETWORK PROGRAMMING CSC- 341 25 Instructor: Junaid Tariq, Lecturer, Department of Computer Science 26 9 Lecture Sockets as means for inter-process communication (IPC) application layer Client Process Socket

More information

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Looping and Counting. Lecture 3 Hartmut Kaiser  hkaiser/fall_2012/csc1254.html Looping and Counting Lecture 3 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html Abstract First we ll discuss types and type safety. Then we will modify the program

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator C++ Addendum: Inheritance of Special Member Functions Constructors Destructor Construction and Destruction Order Assignment Operator What s s Not Inherited? The following methods are not inherited: Constructors

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

CSE 333 Final Exam June 6, 2017 Sample Solution

CSE 333 Final Exam June 6, 2017 Sample Solution Question 1. (24 points) Some C and POSIX I/O programming. Given an int file descriptor returned by open(), write a C function ReadFile that reads the entire file designated by that file descriptor and

More information

Exercise 1.1 Hello world

Exercise 1.1 Hello world Exercise 1.1 Hello world The goal of this exercise is to verify that computer and compiler setup are functioning correctly. To verify that your setup runs fine, compile and run the hello world example

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

C++14 Reflections Without Macros, Markup nor External Tooling

C++14 Reflections Without Macros, Markup nor External Tooling C++14 Reflections Without Macros, Markup nor External Tooling Metaprogramming Tricks for POD Types Antony Polukhin Boost libraries maintainer (DLL, LexicalCast, Any, TypeIndex, Conversion) + Boost.CircularBuffer,

More information

Threaded Programming. Lecture 9: Alternatives to OpenMP

Threaded Programming. Lecture 9: Alternatives to OpenMP Threaded Programming Lecture 9: Alternatives to OpenMP What s wrong with OpenMP? OpenMP is designed for programs where you want a fixed number of threads, and you always want the threads to be consuming

More information

C++ Namespaces, Exceptions

C++ Namespaces, Exceptions C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design http://www.cplusplus.com/doc/tutorial/namespaces/ http://www.cplusplus.com/doc/tutorial/exceptions/ http://www.cplusplus.com/doc/tutorial/typecasting/

More information

Lecture 7. Followup. Review. Communication Interface. Socket Communication. Client-Server Model. Socket Programming January 28, 2005

Lecture 7. Followup. Review. Communication Interface. Socket Communication. Client-Server Model. Socket Programming January 28, 2005 Followup symbolic link (soft link): pathname, can be across file systems, replacement of file will be active on all symbolic links, consumes at least an inode. hard link: pointers to an inode, only in

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

CSE 333 Final Exam June 8, 2016 Sample Solution

CSE 333 Final Exam June 8, 2016 Sample Solution Question 1. (18 points) A bit of C++ coding. In this problem we would like to implement parts of an inverted document index related to, but (much) simpler than, the project code we built this quarter.

More information

Signal Example 1. Signal Example 2

Signal Example 1. Signal Example 2 Signal Example 1 #include #include void ctrl_c_handler(int tmp) { printf("you typed CTL-C, but I don't want to die!\n"); int main(int argc, char* argv[]) { long i; signal(sigint, ctrl_c_handler);

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

SOCKETLIB. Requirements

SOCKETLIB. Requirements SOCKETLIB SocketLib is an event based, semi-asynchronous socket stream. It derives from standard C++ sockets, therefore, all extractors (>>) and inserters (

More information

The C++ Object Lifecycle. EECS 211 Winter 2019

The C++ Object Lifecycle. EECS 211 Winter 2019 The C++ Object Lifecycle EECS 211 Winter 2019 2 Initial code setup $ cd eecs211 $ curl $URL211/lec/09lifecycle.tgz tar zx $ cd 09lifecycle 3 Road map Owned string type concept Faking it An owned string

More information

disspcap Documentation

disspcap Documentation disspcap Documentation Release 0.0.1 Daniel Uhricek Dec 12, 2018 Installation 1 Requirements 3 1.1 Build depedencies............................................ 3 1.2 Python depedencies...........................................

More information

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each). A506 / C201 Computer Programming II Placement Exam Sample Questions For each of the following, choose the most appropriate answer (2pts each). 1. Which of the following functions is causing a temporary

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Generic Programming in C++: A modest example

Generic Programming in C++: A modest example Generic Programming in C++: A modest example Marshall Clow Qualcomm Technologies, Inc. mclow@qti.qualcomm.com marshall@idio.com http://cplusplusmusings.wordpress.com Twitter: @mclow Problem Definition

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

6.S096 Lecture 4 Style and Structure

6.S096 Lecture 4 Style and Structure 6.S096 Lecture 4 Style and Structure Transition from C to C++ Andre Kessler Andre Kessler 6.S096 Lecture 4 Style and Structure 1 / 24 Outline 1 Assignment Recap 2 Headers and multiple files 3 Coding style

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

Processes. Johan Montelius KTH

Processes. Johan Montelius KTH Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other

More information

Unified Modeling Language a case study

Unified Modeling Language a case study Unified Modeling Language a case study 1 an online phone book use case diagram encapsulating a file 2 Command Line Arguments arguments of main arrays of strings 3 Class Definition the filesphonebook.h

More information

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary Slide Set 14 for ENCM 339 Fall 2016 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary November 2016 ENCM 339 Fall 2016 Slide Set 14 slide 2/35

More information

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Looping and Counting. Lecture 3. Hartmut Kaiser  hkaiser/fall_2011/csc1254.html Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract First we ll discuss types and type safety. Then we will modify the program we developed last time (Framing

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects

More information

UNDEFINED BEHAVIOR IS AWESOME

UNDEFINED BEHAVIOR IS AWESOME UNDEFINED BEHAVIOR IS AWESOME Piotr Padlewski piotr.padlewski@gmail.com, @PiotrPadlewski ABOUT MYSELF Currently working in IIIT developing C++ tooling like clang-tidy and studying on University of Warsaw.

More information

A process. the stack

A process. the stack A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Assignment 2 Group 5 Simon Gerber Systems Group Dept. Computer Science ETH Zurich - Switzerland

Assignment 2 Group 5 Simon Gerber Systems Group Dept. Computer Science ETH Zurich - Switzerland Assignment 2 Group 5 Simon Gerber Systems Group Dept. Computer Science ETH Zurich - Switzerland t Your task Write a simple file server Client has to be implemented in Java Server has to be implemented

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

Chapter 4: Processes

Chapter 4: Processes Chapter 4: Processes Process Concept Process Scheduling Operations on Processes Cooperating Processes Interprocess Communication Communication in Client-Server Systems 4.1 Process Concept An operating

More information

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017 C++\CLI Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017 Comparison of Object Models Standard C++ Object Model All objects share a rich memory model: Static, stack, and heap Rich object life-time

More information

lecture04: Constructors and Destructors

lecture04: Constructors and Destructors lecture04: Largely based on slides by Cinda Heeren CS 225 UIUC 13th June, 2013 Announcements lab debug due Saturday night (6/15) mp1 due Monday night (6/17) Warmup: what happens? /** @file main.cpp */

More information

Making New Pseudo-Languages with C++

Making New Pseudo-Languages with C++ Making New Pseudo-Languages with C++ Build You a C++ For Great Good ++ A 10,000 Metre Talk by David Williams-King Agenda 1/4 Introduction 2/4 Polymorphism & Multimethods 3/4 Changing the Behaviour of C++

More information

libcppa Now: High-Level Distributed Programming Without Sacrificing Performance

libcppa Now: High-Level Distributed Programming Without Sacrificing Performance libcppa Now: High-Level Distributed Programming Without Sacrificing Performance Matthias Vallentin matthias@bro.org University of California, Berkeley C ++ Now May 14, 2013 Outline 1. Example Application:

More information

Remedial C Now that we can actually use it Pete Williamson

Remedial C Now that we can actually use it Pete Williamson Remedial C++ 11 Now that we can actually use it Pete Williamson (petewil00@hotmail.com) Overview (1) auto lambdas nullptr = default, = delete shared_ptr Range based for loops Overview (2) Uniform initialization

More information

Direct Memory Access. Lecture 2 Pointer Revision Command Line Arguments. What happens when we use pointers. Same again with pictures

Direct Memory Access. Lecture 2 Pointer Revision Command Line Arguments. What happens when we use pointers. Same again with pictures Lecture 2 Pointer Revision Command Line Arguments Direct Memory Access C/C++ allows the programmer to obtain the value of the memory address where a variable lives. To do this we need to use a special

More information

There are, of course, many other possible solutions and, if done correctly, those received full credit.

There are, of course, many other possible solutions and, if done correctly, those received full credit. Question 1. (20 points) STL. Complete the function ChangeWords below. This function has as inputs a vector of strings, and a map of key-value pairs. The function should return a new vector

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract

More information

CSE 12 Spring 2016 Week One, Lecture Two

CSE 12 Spring 2016 Week One, Lecture Two CSE 12 Spring 2016 Week One, Lecture Two Homework One and Two: hw2: Discuss in section today - Introduction to C - Review of basic programming principles - Building from fgetc and fputc - Input and output

More information

Why C++ is much more fun than C (C++ FAQ)?

Why C++ is much more fun than C (C++ FAQ)? From C to C++ Why C++ is much more fun than C (C++ FAQ)? 1. Classes & methods - OO design 2. Generic programming - Templates allow for code reuse 3. Stricter type system (e.g. function args) 4. Some run-time

More information

Exercise Session 2 Simon Gerber

Exercise Session 2 Simon Gerber Exercise Session 2 Simon Gerber CASP 2014 Exercise 2: Binary search tree Implement and test a binary search tree in C: Implement key insert() and lookup() functions Implement as C module: bst.c, bst.h

More information

GCC : From 2.95 to 3.2

GCC : From 2.95 to 3.2 GCC : From 2.95 to 3.2 Topics Simple changes name of standard include files, std::endl, iostream, throw statements, vector iterators More complicated changes string streams, parameterized macros, hash_map

More information

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck C++ Crash Kurs Exceptions Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Exceptions: Introduction What are exceptions Exceptions are

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

Socket Programming for TCP and UDP

Socket Programming for TCP and UDP CSCI4430 Data Communication and Computer Networks Socket Programming for TCP and UDP ZHANG, Mi Jan. 19, 2017 Outline Socket Programming for TCP Introduction What is TCP What is socket TCP socket programming

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

LibSerial Documentation

LibSerial Documentation LibSerial Documentation Release 1.0.0rc1 CrayzeeWulf Apr 05, 2018 Contents: 1 Feature Summary 3 2 Description 5 3 Download 7 4 Install 9 5 Tutorial 11 5.1 Opening a Serial Port I/O Stream....................................

More information

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

So far, system calls have had easy syntax. Integer, character string, and structure arguments. Pointers Page 1 So far, system calls have had easy syntax Wednesday, September 30, 2015 10:45 AM Integer, character string, and structure arguments. But this is not always true. Today, we begin to explore

More information

Base Component. Chapter 1. *Memory Management. Memory management Errors Exception Handling Messages Debug code Options Basic data types Multithreading

Base Component. Chapter 1. *Memory Management. Memory management Errors Exception Handling Messages Debug code Options Basic data types Multithreading Chapter 1. Base Component Component:, *Mathematics, *Error Handling, *Debugging The Base Component (BASE), in the base directory, contains the code for low-level common functionality that is used by all

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 20 November 12, 2018 CPSC 427, Lecture 20, November 12, 2018 1/26 Rethrowing Exceptions Uncaught Exceptions Singleton Design Pattern Smart

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017 Next week s homework Classes: Methods, Constructors, Destructors and Assignment Read Chapter 7 Your next quiz will be on Chapter 7 of the textbook For : COP 3330. Object oriented Programming (Using C++)

More information

C++ Programming Lecture 7 Software Engineering Group

C++ Programming Lecture 7 Software Engineering Group C++ Programming Lecture 7 Software Engineering Group Philipp D. Schubert Contents 1. Template metaprogramming 2. Variadic template arguments 3. Smart pointer Template metaprogramming Template metaprogramming

More information

CSC 1600 Memory Layout for Unix Processes"

CSC 1600 Memory Layout for Unix Processes CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant

More information

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review) Announcements Lecture 05a Sept. 19 th, 2017 9/19/17 CS253 Fall 2017 Bruce Draper 1 Quiz #4 due today (before class) PA1/2 Grading: If something is wrong with your code, you get sympathy PA3 is due today

More information

EECS 482 Introduction to Operating Systems

EECS 482 Introduction to Operating Systems EECS 482 Introduction to Operating Systems Fall 2017 Manos Kapritsos Slides by: Harsha V. Madhyastha Recap: Socket abstraction Machine 1 Machine 2 Process A Process B Process C socket 1 socket 2 socket

More information