When talking to the sensors during the next exercises we will use a Raspberry Pi to do the readout. Two different libraries are available to easily interface to the sensors:
pigpio ( http://abyz.co.uk/rpi/pigpio and
wiringpi (https://projects.drogon.net/raspberry-pi/wiringpi)
In analogy to the way we read and write pipes we will first try to write some text to a file and read it back with another program.
Write a C program called fileWrite.c which writes the text:
hello #1
hello #2
hello #3
to a text file. This file should be readable to anybody but writable only to its owner and members of the group owning the file. Name the file “text.txt”. Use the system calls
open
write/read
close
Check that the file has been created and use cat/more/less or an editor to look at its content.
Then write a new program fileRead.c to read back its content into a buffer and print out the result with printf.
As an additional exercise you may try to do the same thing with fopen, fwrire, fread, fclose. What is the difference?
This exercises demonstrates the communication between two processes via pipes:
Write a program that creates a pipe using the pipe system call. Have a look at the man page for pipe to get more information about this call. Then your program will spawn a second process (use the system call fork), close the unused pipe ends and send some message from the child process to the parent process who prints the message. Compare writing and reading of pipes to writing and reading files.
Now we will communicate between 2 machines: You will have to write 2 programs:
a tcp server
a tcp client
The server opens a socket with the socket system call. Have a look at the sockaddr_in structure which must be filled before you can bind to the socket. Use port no 5001 for your server.
Once bind was successful (test it!) listen for connect requests on this socket and accept them. Then read messages coming from the client and answer them (e.g. saying:”I saw your message ...”);
These are is the sequence of actions to make the server work:
create a socket (socket system call)
clear and then fill the sockaddr_in structure
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
bind to the socket
listen to the socket
if there is a connection request accept it
read/write from the socket
close socket
The client must
create a socket with the socket system call
fill the sockaddr_in data structure
connect to the server socket
read/write from/to the socket
close it