I have a problem trying to compare the uart input data (from a GPS) with '$' in order to detect a new package. I am sure that the problem is in how I manipulate the charRead variable. I tried one thousand of things, but probably because of my inexperience I have not figured out what it is the problem.
The code compiles and the data is coming all the time, but once I load the code into the beaglebone, it gets stacked but and it doesn't enter in the "if (charRead =='$')".
Thank you in advance!
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>
#include <iostream>
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <limits.h>
#include "Payload.h"
#define SLOTS "/sys/devices/bone_capemgr.9/slots"
#define CR 0x0d
#define SPACE 0x20
#define COMMA 0x2C
#define MAXSIZE 100
unsigned long time_data;
unsigned int button = 45;
int i,z =0, j=0, value;
int rx_length;
int main()
{
//uart4 configuration using termios
int fd;
//unsigned char *mess;
unsigned int value = 0;
gpio_export(button);
//Wait until the button is pushed
while (value != 1){
if (z==0){
printf("waiting\n");}
z++;
gpio_get_value(button, &value);}
//OPEN THE UART
//open uart4 for tx/rx, not controlling device
if((fd = open("/dev/ttyO4", O_RDONLY | O_NOCTTY|O_NONBLOCK)) < 0){
printf("Unable to open uart4 access.\n");
}
termios uart4;
cfsetospeed(&uart4, B9600); //Set the speed
//set attributes of uart4
uart4.c_iflag = 0;
uart4.c_oflag = 0;
uart4.c_lflag = 0;
tcsetattr(fd, TCSANOW, &uart4);
//----- CHECK FOR ANY RX BYTES -----
// Read up to 100 characters from the port if they are there
unsigned char stringRead[MAXSIZE];
unsigned char charRead;
do{
if (rx_length = read(fd, (void*)charRead, MAXSIZE)>0){
if (charRead =='$'){
i=0;
stringRead[i] = charRead; //Store in the first position of the char --> $
do {
rx_length = read(fd, (void*)charRead, MAXSIZE); //Read the next bit
if( (charRead != '\0') ) {
i++;
stringRead[i] = charRead; //write into stringRead
}
} while(charRead != 'CR'); //ASCII Carriage Return
stringRead[i+1] = charRead;
printf("%s", stringRead);
}}
if (rx_length==0){
//No data
}
gpio_get_value(button, &value);
}while (value!=0);
gpio_unexport(button);
close(fd);
return 0;
}
You're passing a cast of the variable value of charRead rather than a pointer to a memory location as the function read() expects void *.
read(fd, (void*)charRead, MAXSIZE)
You need to either read one character at a time:
read(fd, &charRead, 1)
Or change your reading logic to maximize amount read and data processing. I also recommend adding a bounds check on accessing stringRead.
// The following should handle the reading of a GPS NMEA message and display it
// I have not run the program, but compiling it was successful
// note:
// 1) the handling of the 'i' variable
// 2) the calls to reading the GPS input
// 3) the handling of error conditions
// 4) the simple logic flow
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>
//#include <iostream> // this is not C++ so this line not needed
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <limits.h>
#include "Payload.h"
// #define SLOTS "/sys/devices/bone_capemgr.9/slots" // not used, raises compiler warning
#define CR (0x0D)
// #define SPACE (0x20) // not used, raises compiler warning
// #define COMMA (0x2C) // not used, raises compiler warning
#define MAXSIZE (100)
#define BUTTON_PORT (45)
// unsigned long time_data; // not used, raises compiler warning
// int j=0; // not used, raises compiler warning
// int value = 0; // not used, raises compiler warning about variable masking
int main()
{
int i;
int z = 0; // flag used to control execution flow
int rx_length; // return status value from read()
//uart4 configuration using termios
int fd; // file descriptor number
//unsigned char *mess; // not used, raises compiler warning
unsigned int value = 0;
gpio_export(BUTTON_PORT);
//Wait until the button is pushed
// burn mass CPU cycles, while waiting
while (0 == value)
{
if (z==0)
{
printf("waiting\n");
z++; // to stop re-entry to this 'if' block
}
// suggest using nsleep() to free up CPU
gpio_get_value(BUTTON_PORT, &value);
} // end while
//open uart4 for rx
if((fd = open("/dev/ttyO4", O_RDONLY | O_NOCTTY|O_NONBLOCK)) < 0)
{
perror("open failed for /dev/tty04");
exit(1);
}
// implied else, open successful
termios uart4;
cfsetospeed(&uart4, B9600); //Set the speed to match the GPS output
//set attributes of uart4
// Note: probably better to read the current termois values
// then modify them to the desired states
uart4.c_iflag = 0;
uart4.c_oflag = 0;
uart4.c_lflag = 0;
tcsetattr(fd, TCSANOW, &uart4);
//----- CHECK FOR ANY RX BYTES -----
// Read up to 100 characters from the port if they are there
unsigned char stringRead[MAXSIZE]; // will contain a GPS NMEA message
unsigned char charRead; // input buffer
do{
while(1)
{
rx_length = read(fd, &charRead, 1);
if( 0 == rx_length )
{ // this will execute a lot since fd set to non-blocking
; // do nothing, while hogging CPU cycles
// suggest using nsleep() to free CPU
}
else if( 0 > rx_length )
{
perror( "read failed" );
exit(1);
}
else if (charRead =='$')
{
stringRead[0] = charRead; //Store first char of NMEA GPS message
i=1; // index for second char of NMEA message from GPS
}
else
{
stringRead[i] = charRead; //Store char
i++; // index for next char into stringRead buffer
if( MAXSIZE <= i )
{ // then overrun input buffer
perror( "read- overrun input buffer, GPS message too long");
exit(2);
}
if( CR == charRead ) //ASCII Carriage Return - end of message
{ // then, got complete message
break; // exit read loop, so can process message
}
} // end if
} // end while
stringRead[i] = '\0'; // terminate string so it can be printed
printf("%s", stringRead);
// get button state via BUTTON_PORT(45)
gpio_get_value(BUTTON_PORT, &value);
} while (value!=0); // then read next gps message
gpio_unexport(BUTTON_PORT);
close(fd);
return 0;
}
Related
First of all, I don't know if I can explain well my problem or you can get it in the appropriate way. But I will try to make it clear for you.
In fact, I have two different C programs.
The first one is a simple loop print of a message on the console :
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main ()
{
while(1)
{
printf("WAITING\n");
sleep(1);
}
}
The second one is a blocking program that waits for an event ( press button ) to turn on led in my embedded board.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <errno.h>
#include <linux/input.h>
#define BTN_FILE_PATH "/dev/input/event0"
#define LED_PATH "/sys/class/leds"
#define green "green"
void change_led_state(char *led_path, int led_value)
{
char lpath[64];
FILE *led_fd;
strncpy(lpath, led_path, sizeof(lpath) - 1);
lpath[sizeof(lpath) - 1] = '\0';
led_fd = fopen(lpath, "w");
if (led_fd == NULL) {
fprintf(stderr, "simplekey: unable to access led\n");
return;
}
fprintf(led_fd, "%d\n", led_value);
fclose(led_fd);
}
void reset_leds(void)
{
change_led_state(LED_PATH "/" green "/brightness", 0);
}
int configure_leds(void)
{
FILE *l_fd;
FILE *r_fd;
char *none_str = "none";
/* Configure leds for hand control */
r_fd = fopen(LED_PATH "/" green "/trigger", "w");
fprintf(r_fd, "%s\n", none_str);
fclose(r_fd);
/* Switch off leds */
reset_leds();
return 0;
}
void eval_keycode(int code)
{
static int green_state = 0;
switch (code) {
case 260:
printf("BTN left pressed\n");
/* figure out red state */
green_state = green_state ? 0 : 1;
change_led_state(LED_PATH "/" green "/brightness", green_state);
break;
}
}
int main(void)
{
int file;
/* how many bytes were read */
size_t rb;
int ret;
int yalv;
/* the events (up to 64 at once) */
struct input_event ev[64];
char *str = BTN_FILE_PATH;
printf("Starting simplekey app\n");
ret = configure_leds();
if (ret < 0)
exit(1);
printf("File Path: %s\n", str);
if((file = open(str, O_RDONLY)) < 0) {
perror("simplekey: File can not open");
exit(1);
}
for (;;) {
/* Blocking read */
rb= read(file, &ev, sizeof(ev));
if (rb < (int) sizeof(struct input_event)) {
perror("simplekey: short read");
exit(1);
}
for (yalv = 0;
yalv < (int) (rb / sizeof(struct input_event));
yalv++) {
if (ev[yalv].type == EV_KEY) {
printf("%ld.%06ld ",
ev[yalv].time.tv_sec,
ev[yalv].time.tv_usec);
printf("type %d code %d value %d\n",
ev[yalv].type,
ev[yalv].code, ev[yalv].value);
/* Change state on button pressed */
if (ev[yalv].value == 0)
eval_keycode(ev[yalv].code);
}
}
}
close(file);
reset_leds();
exit(0);
}
When I execute the second code, the program starts waiting for the event to switch on/off the led.
My question is :
How can I make interaction between the two programs ? I want to execute the firs one --> It starts printing for me " WAITING " until I press the BUTTON --> the LED turn on --> and then it goes back to the first program and re-start printing " WAITING " on the console.
I don't know if I explained well the issue but I hope that you can help me! Thank you.
You need a communication mechanism between your two programs. This is also known als inter-process communication.
Generally, you have several options to achieve this (depending on the operating system you are using, not all of them may be available):
Shared memory / shared files
Message passing (e.g. via sockets)
Pipes
Signals
A helpful introduction can be found here.
I am trying to write a function that reads a chunk of data sent through UART. I am using Raspbian Jessie running on a RaspberryPi model B but I wanted to use this C code (with any necessary revisions) on openwrt. So far, this is what I wrote.
Header:
#ifndef __UART_LIB__
#define __UART_LIB__
#include <stdlib.h> //Errors, etc
#include <unistd.h> //Used for UART
#include <fcntl.h> //Used for UART
#include <termios.h> //Used for UART
#include <sys/types.h> //These includes are for timeout
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h> //
#include <sys/ioctl.h>
#define BITS_PER_PACKAGE_ 11
#define WAIT_PROLONGATION_CONSTANT_ 1.1f
//Some values used by default, left for the user to change if needed
unsigned int BAUD_ ;
unsigned int NUM_BITS_ ;
char *UART_PATH_ ;
unsigned int MAX_SIZE_ ;
unsigned int OPEN_FLAG_ ;
time_t TIMEOUT_SEC_ ;
suseconds_t TIMEOUT_USEC_ ;
struct timeval WAIT_CONSTANT_ ;
int open_conf_UART_() ;
int read_UART_(int uart_filestream, char** dest, int max_len) ;
#endif
.c file:
#include "uartlib.h"
unsigned int BAUD_ = B115200 ;
unsigned int NUM_BITS_ = CS8 ;
char *UART_PATH_ = "/dev/ttyAMA0" ;
unsigned int MAX_SIZE_ = 128 ;
unsigned int OPEN_FLAG_ = O_RDWR ;
time_t TIMEOUT_SEC_ = 5 ;
suseconds_t TIMEOUT_USEC_ = 0 ;
int open_conf_UART_()
{
int indicator, old_fl;
int uart_filestream ;
struct termios options ;
// Opening the port in a read/write mode
uart_filestream = open(UART_PATH_, OPEN_FLAG_ | O_NOCTTY );
if (uart_filestream < 0)
{
// Unable to open the serial port, so produce an error and halt
return -1;
}
// Configuring the options for UART
// Retrieve the options and modify them.
indicator = tcgetattr(uart_filestream, &options);
if(indicator < 0)
{
// Unable to get the attributes
close(uart_filestream);
return -1;
}
// I found a question on stackoverlow where the answer said that VTIME and VMIN will be ignored unless I
// switch the FNDELAY flag off
old_fl = fcntl(uart_filestream, F_GETFL);
if(old_fl < 0)
{
return -1;
}
old_fl &= ~FNDELAY;
fcntl(uart_filestream, old_fl);
//Setting the options
options.c_cflag = CRTSCTS | BAUD_ | NUM_BITS_ | CLOCAL | CREAD ;
options.c_iflag = 0;
options.c_oflag = 0;
options.c_lflag = 0;
//I want the uart to wait 1/10 of a second between bytes at most
options.c_cc[VTIME] = 1;
options.c_cc[VMIN] = 0;
// Flushing the file stream (the input and the output area)
indicator = tcflush(uart_filestream, TCIOFLUSH);
if(indicator < 0)
{
// Unable to flush
close(uart_filestream);
return -1;
}
// Setting the options for the file stream.
indicator = tcsetattr(uart_filestream, TCSANOW, &options);
if(indicator < 0)
{
// Unable to set the attributes
close(uart_filestream);
return -1;
}
return uart_filestream;
}
int read_UART_(int uart_filestream, char** dest, int max_len)
{
int indicator;
int buffer_length;
indicator = tcflush(uart_filestream, TCIFLUSH);
if(indicator < 0)
{
// Unable to flush
return -1;
}
//Do the actual reading
buffer_length = read(uart_filestream, (void*)(*dest), max_len);
if(indicator < 0)
{
return -1;
}
else
{
// Returning number of read bytes
return buffer_length;
}
// Both branches of the if statement above have return, so this will not be reached
}
So, when I try to read more than 8 bytes, the message gets truncated to 8 bytes.
As I read, setting VTIME to a certain value allows the time interval between two bytes to be at most that long.
I am not certain what is going on but I suspect that the read() call reads the buffer before the receiving of the data is complete.
My wish is to read a chunk of data of undefined size. I also used select() with a timeout before the read to make sure the program won't block entirely.
I read a lot of forum topics, stackoverflow questions, guides, etc. on this topic and none seem to help me with my solution.
So, can anyone explain what is going on here? Is it possible to do what I want?
Note that I removed some of the code (I also wrote a function that writes to a UART port) so here might be some redundant includes, global variables, etc.
So, I solved my problem. I still can't flush (when the system is freshly booted up and there was a signal before I turned my program on, there is some old content in the buffer, as it seems to me).
I used this assumption: The package will arrive in smaller bursts and they will be separated by TIMEOUT_BYTE_ amount of time. If that expires, I assume that the package is over.
Also, I have a timeout for initial waiting for the data but I reckon that is situational.
Header file:
#ifndef UART_LIB_
#define UART_LIB_
#include <stdlib.h> //Errors, etc
#include <unistd.h> //Used for UART
#include <fcntl.h> //Used for UART
#include <termios.h> //Used for UART
#include <sys/types.h> //These includes are for timeout
#include <sys/select.h> //Used for select(), etc
//Some values used by default, left for the user to change if needed
//Used to set up the baud rate
unsigned int BAUD_ ;
//Used to indicate number of bits in one backage
unsigned int NUM_BITS_ ;
//Path to the UART device
char *UART_PATH_ ;
//Flag for opening the device
unsigned int OPEN_FLAG_ ;
//Timeout for answer from the other side
time_t TIMEOUT_SEC_ ;
suseconds_t TIMEOUT_USEC_ ;
//Time interval between two bursts of data inside the package
suseconds_t TIMEOUT_BYTE_ ;
int open_conf_UART_(void) ;
int read_UART_(int uart_filestream, char* dest, int max_len) ;
#endif
Source file:
#include <errno.h>
#include "uartlib.h"
unsigned int BAUD_ = B38400 ;
unsigned int NUM_BITS_ = CS8 ;
char *UART_PATH_ = "/dev/ttyAMA0" ;
unsigned int OPEN_FLAG_ = O_RDWR ;
time_t TIMEOUT_SEC_ = 2 ;
suseconds_t TIMEOUT_USEC_ = 0 ;
// This needs to be finely tuned
suseconds_t TIMEOUT_BYTE_ = 5000;
int open_conf_UART_()
{
// Variable section
int indicator;
int uart_filestream ;
struct termios options ;
// Opening the port in a read/write mode
uart_filestream = open(UART_PATH_, OPEN_FLAG_ | O_NOCTTY | O_NONBLOCK);
if (uart_filestream < 0)
{
// Unable to open the serial port, so produce an error and halt
return -1;
}
// Configuring the options for UART
// Flushing the file stream (the input and the output area)
indicator = tcflush(uart_filestream, TCIOFLUSH);
if(indicator < 0)
{
// Unable to flush
close(uart_filestream);
return -1;
}
// Retrieve the options and modify them.
indicator = tcgetattr(uart_filestream, &options);
if(indicator < 0)
{
// Unable to get the attributes
close(uart_filestream);
return -1;
}
// Setting the options
cfmakeraw(&options);
options.c_cflag |= BAUD_ | NUM_BITS_ | CREAD;
// Setting the options for the file stream.
indicator = tcsetattr(uart_filestream, TCSANOW, &options);
if(indicator < 0)
{
// Unable to set the attributes
close(uart_filestream);
return -1;
}
return uart_filestream;
}
int read_UART_(int uart_filestream, char* dest, int max_len)
{
// Variable section
int indicator;
int buffer_length;
char *tmp_dest;
fd_set set;
struct timeval timeout, init_timeout;
while(1)
{
// Reseting the set and inserting the uart_filestream in it
FD_ZERO(&set);
FD_SET(uart_filestream, &set);
// Setting the time for initial contact
init_timeout.tv_sec = TIMEOUT_SEC_ ;
init_timeout.tv_usec = TIMEOUT_USEC_ ;
// Waiting for the first contact. If this times out, we assume no contact.
indicator = select(uart_filestream + 1, &set, NULL, NULL, &init_timeout);
if(indicator < 0)
{
if(errno == EINTR)
{
// Try again
continue;
}
return -1;
}
else if(indicator == 0)
{ // Timeout has occurred
return -2;
}
else
{
break;
}
}
// This section means that there is something to be read in the file descriptor
buffer_length = 0 ;
tmp_dest = dest ;
// The first select is redundant but it is easier to loop this way.
while(buffer_length < max_len)
{
// select changes the timeval structure so it is reset here
timeout.tv_sec = 0;
timeout.tv_usec = TIMEOUT_BYTE_;
// Reinitialize the sets for reading
FD_ZERO(&set);
FD_SET(uart_filestream, &set);
// Wait for the file descriptor to be available or for timeout
indicator = select(uart_filestream+1, &set, NULL, NULL, &timeout);
if(indicator < 0)
{
if(errno == EINTR)
{
// Try again
continue;
}
// This indicates an error
return -1;
}
else if(indicator == 0)
{
// This indicates a timeout; We assume that the transmission is over once first timeout is reached
return buffer_length;
}
// There's been a select that didn't time out before this read
indicator = read(uart_filestream, (void*)tmp_dest, max_len - buffer_length);
if(indicator < 0)
{
if(errno == EINTR)
{
// If the call was interrupted, try again
continue;
}
// If it was any other condition, the read is corrupt.
return -1;
}
else if(indicator == 0)
{
// If, somehow, EOF was reached
break;
}
// Change the necessary values
buffer_length += indicator ;
tmp_dest += indicator;
}
// Both branches of the if statement above have return, so this will not be reached
// but a warning is generated
return buffer_length;
}
void flush_buffer_UART_(int uart_filestream)
{
char c;
while(read(uart_filestream, &c, 1) > 0);
}
I know it is not the topic here, but if someone knows how to solve the flush issue, please respond.
Also, any constructive criticism is very welcome.
P.S. I also have a write_UART() function but I did not deem necessary to post it as it represented no problem (measured with an oscilloscope and later, tried with echo. Echo wouldn't be able to give me the same message).
EDIT: Flush has been introduced and then merged with the source file. Still haven't figured out is it working or not.
I am using this source code to read from the serial port of a linux machine. I am able to read from the port, but all of the values are in ascii gibberish ( i am reading the input from an xbox controller). I know I am sending it correctly, i.e. i can see on my side I am sending -128 - 127 as a char, but when I am converting it on my linux machine using atoi its returning 0, or when I try to cast the data to int it returns -48 , equivalent to 0 in ascii.
Is there a way for me to convert the incoming ascii into a readable integer like 64 or -114? I appreciate any help, thank you.
#include <stdlib.h>
#include <stdio.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include "rs232.h"
int main()
{
int i, n,
cport_nr=0, /* /dev/ttyS0 (COM1 on windows) */
bdrate=9600; /* 9600 baud */
unsigned char buf[4096];
char mode[]={'8','N','1',0};
if(RS232_OpenComport(cport_nr, bdrate, mode))
{
printf("Can not open comport\n");
return(0);
}
while(1)
{
n = RS232_PollComport(cport_nr, buf, 4095);
if(n > 0)
{
buf[n] = 0; /* always put a "null" at the end of a string! */
for(i=0; i < n; i++)
{
if(buf[i] < 32) /* replace unreadable control-codes by dots */
{
buf[i] = '.';
}
}
printf("received %i bytes: %s\n", n, (char *)buf);
}
#ifdef _WIN32
Sleep(100);
#else
usleep(100000); /* sleep for 100 milliSeconds */
#endif
}
return(0);
}
I have an instrument which I need to talk to by RS232. I am using C and following is the code. The problem is that, when I try to read field value (reading from meter) which is 11 byte long, one read command is reading only 8 bytes and subsequently I have to issue another read command which gives me final 3 bytes. Finally I am concatenating both read buffers to make final meaningful value.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXWAIT 30
#define BAUDRATE B9600
#define TESLAMETER "/dev/ttyS0"
#define _POSIX_SOURCE 1 /* POSIX compliant source */
#define FALSE 0
#define TRUE 1
#define NOREAD 255
volatile int STOP = FALSE;
int fd;
struct termios oldtp, newtp;
int openComPort(void)
{
fd = open(TESLAMETER, O_RDWR | O_NOCTTY |O_NDELAY );
if (fd <0)
{
perror(TESLAMETER);
return fd;
}
else
fcntl(fd,F_SETFL,0);
tcgetattr(fd,&oldtp); /* save current serial port settings */
bzero(&newtp, sizeof(newtp));
newtp.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
newtp.c_iflag = IGNPAR | ICRNL;
newtp.c_oflag = 0;
newtp.c_lflag = 0;//ICANON;
newtp.c_cc[VINTR] = 0; /* Ctrl-c */
newtp.c_cc[VQUIT] = 0; /* Ctrl-\ */
newtp.c_cc[VERASE] = 0; /* del */
newtp.c_cc[VKILL] = 0; /* # */
newtp.c_cc[VEOF] = 4; /* Ctrl-d */
newtp.c_cc[VTIME] = 1; /* inter-character timer unused, 0.5 seconds read timeout */
newtp.c_cc[VMIN] = 0; /* blocking or non blocking read until 1 character arrives */
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtp);
return fd;
}
float readMagField()
{
unsigned char cmd[]="FA0\r"; // Read Field
char buff2[11] = {0x00};
char buff3[11] = {0x00};
float fieldFloat = 0.00;
int n_written= 0, spot = 0, res;
do
{
n_written = write( fd, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
if (n_written < 0)
{
printf("write() of 4 bytes failed!\n");
return FALSE;
}
else
{
//printf("Field Read Command sent successfully %d\n",n_written);
res = read(fd,buff2,11); // Reads 8 bytes
res = read(fd,buff3,11); // Reads remaining 3 bytes
fieldFloat = atof(strcat(buff2,buff3)); // Final string of 11 bytes here
return fieldFloat;
}
}
Is there something that I am doing or setting wrong? Because, I can read the complete set of characters in one go using Python serial module, but not in C. I am working on Ubuntu 12.04 LTS.
read() may return without reading the specified length.
read(2) - Linux manual page
RETURN VALUE
On success, the number of bytes read is returned (zero indicates end
of file), and the file position is advanced by this number. It is
not an error if this number is smaller than the number of bytes
requested; this may happen for example because fewer bytes are
actually available right now (maybe because we were close to end-of-
file, or because we are reading from a pipe, or from a terminal), or
because read() was interrupted by a signal. See also NOTES.
How about retrying until the desired length of data have been read?
ssize_t read2(int fd, void *buf, size_t count) {
ssize_t read_length = 0;
while (read_length < count) {
ssize_t delta = read(fd, buf + read_length, count - read_length);
if (delta == -1) return -1;
read_length += delta;
}
return read_length;
}
I'm currently doing my assignment and it's compulsory to use C-Free 5.0. Just need your help to solve this piece of puzzle. I want to implement a time limit for the user to input an answer before it expires. I've tried this code but it got block at scanf() function. Is there any other method like an unblocking input or something. I've tried to implement '#include <sys/select.h>' but this program doesn't have that library.
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
int main()
{
char st[10];
printf ("Please enter a line of text : ");
time_t end = time(0) + 5; //5 seconds time limit.
while(time(0) < end)
{
scanf("%s", &st);
if(st != NULL)
{
printf ("Thank you, you entered >%s<\n", st);
exit(0);
}
}
main();
}
Here is an example program that shows how you can use O_NONBLOCK flag on a stdin file descriptor.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define INPUT_LEN 10
int main()
{
printf ("Please enter a line of text : ");
fflush(stdout);
time_t end = time(0) + 5; //5 seconds time limit.
int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
char answer[INPUT_LEN];
int pos = 0;
while(time(0) < end)
{
int c = getchar();
/* 10 is new line */
if (c != EOF && c != 10 && pos < INPUT_LEN - 1)
answer[pos++] = c;
/* if new line entered we are ready */
if (c == 10)
break;
}
answer[pos] = '\0';
if(pos > 0)
printf("%s\n", answer);
else
puts("\nSorry, I got tired waiting for your input. Good bye!");
}
Since you have fcntl.h try setting stdin to non-blocking. It's not pretty (active waiting), but if you do not have select then this is the easyest way to go:
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
// get stdin flags
int flags = fcntl(0, F_GETFL, 0);
if (flags == -1) {
// fcntl unsupported
perror("fcntl");
return -1;
}
// set stdin to non-blocking
flags |= O_NONBLOCK;
if(fcntl(0, F_SETFL, flags) == -1) {
// fcntl unsupported
perror("fcntl");
return -1;
}
char st[1024] = {0}; // initialize the first character in the buffer, this is generally good practice
printf ("Please enter a line of text : ");
time_t end = time(0) + 5; //5 seconds time limit.
// while
while(time(0) < end // not timed out
&& scanf("%s", st) < 1 // not read a word
&& errno == EAGAIN); // no error, but would block
if (st[0]) // if the buffer contains something
printf ("Thank you, you entered >%s<\n", st);
return 0;
}
A remark to your code: if (st != NULL) will always be satisfied since st is a stack pointer.