2012-04-21 3 views
1

는 다음 코드를 참조하십시오 :Linux 2.6.23. 수신 중 오류가 발생했습니다. 함수가 반환을 읽어 -1

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <fcntl.h> 
#include <sys/types.h> 
#include <sys/ioctl.h> 
#include <sys/stat.h> 
#include <termios.h> 

#define BAUDRATE B115200 
#define SER_DEVICE "/dev/ttyS0" 
#define FALSE  0 
#define TRUE  1 


int main() 
{ 
int fd,c,res,i,n; 
struct termios oldtio,newtio; 
unsigned char buf[255] = "WELCOME TO THE WORLD OF LINUX PROGRAMMING\n"; 
unsigned char buf2[255]= {"\0"}; 
//Opening a Device for Reading Writing. 
//O_NOCTTY : - The Port Never Becomes the Controlling Terminal of the Process. 
//O_NDELAY : - Use NON-Blocking IO. on some system this also means Deactivating the DCD line. 

fd=open("/dev/ttyS0",O_RDWR | O_NOCTTY | O_NDELAY); 

if(fd<0) 
{ 
printf("\nError in opening the File\n"); 
exit(0); 
} 
else 
{ 
printf("File Opened SuccessFull..HurraYYY !!!!1\n"); 
} 

//printf("--------------Test Begin---------------\n"); 

//Save Current Serial Port Settings 

tcgetattr(fd,&oldtio); 
//clear the struct for New port settings 
memset(&newtio,0,sizeof(newtio)); 

//Baud rate : Set bps rate . 
//You could also use cfsetispeed and cfsetospeed. 
//CRTSCTS : Output Hardware Flow control 
//CS8 : 8n1(8bit No Parity 1 Stopbit) 
//CLOCAL : local connection no modem control 
//CREAD : Enable Receiving character 
//printf("Setting Configuration for Port"); 
newtio.c_cflag |= (BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD); 

//IGNPAR : Ignore bytes with parity error. 
//ICRNL : map CR to NL 
//printf("Setting Parity\n"); 
newtio.c_cflag |= (IGNPAR | ICRNL); 

//RAW output 
//printf("Raw Output\n"); 
newtio.c_oflag = 0; 
//printf("Enabling Canonical format \n"); 
//ICANON : Enable canonical input. 
newtio.c_lflag |= ICANON; 
//printf("Initialising Char\n"); 
//Initialise all characters 
newtio.c_cc[VMIN] = 1; /*Blocking read until one character arrives*/ 
newtio.c_cc[VTIME] = 0; /*Inter character timer unused*/ 

/* 
Now clean the Modem Line and Activate the Settings for the Port. 
*/ 
tcflush(fd,TCIFLUSH); 
printf("Flushing Lines\n"); 
tcsetattr(fd,TCSANOW,&newtio); 


n=write(fd,&buf,42); 
printf("n=%d",n); 


for(i=0;i<sizeof(unsigned int);i++); 

for(i=0;i<sizeof(unsigned int);i++); 
for(i=0;i<sizeof(unsigned int);i++); 
for(i=0;i<200;i++) 
printf(""); 
n=0; 
n = read(fd,&buf2,42); 
if(n==-1) 
{ 
printf("\nError in Receiving"); 
} 
else 
printf("Received String = %s",buf2); 

/* 
Restore the Old Port Setting 
*/ 

tcsetattr(fd,TCSANOW,&oldtio); 

printf("==============TEST END==============\n"); 

close(fd); 
} 

내가 하이퍼 터미널에 표시되는 문자열을 전송할 수입니다. 그러나 Function Read는 값을 -1로 반환합니다. 발견 된 가능성은 다음과 같습니다. 1. 구성을받는 것이 잘못되었습니다. 2. 루프 백이 필요합니다.

루핑을 시도했지만 돌아 가기를 시도했지만 작동하지 않습니다. 내가 (1)

전송 ANS 수신 ... 동안 코드를 실행하고 반환 뭔가를 읽으면! = -1 루프에서 ..break. 하지만 그렇게하는 것은 효과가 없습니다. 읽기/쓰기주기에 추가해야하는 최소 지연은 얼마입니까?

나는 MPC 8641D 프로세서에이 코드를 실행하고 있습니다.

귀하의 제안은 저에게 중요합니다.

귀하의 의견을 기다리고 있습니다. !!!! :)

답변

2

read() 실패의 자세한 이유를 알아 보려면 전역 변수 errno에 저장된 값을 확인해야합니다 (이 내용은 매뉴얼 페이지에서 읽음). 그 쉬운 방법은 실패 메시지를 인쇄 할 때 printf() 대신 perror()을 사용하는 것입니다. perror()는 이유를 알려주는 사람이 읽을 수있는 문자열을 추가합니다.

+1

errno에 직접 액세스하려면'#include '해야합니다. 'strerror (errno)'(C89)는 에러 메시지에 대한 char 포인터를 줄 것이다. – delicateLatticeworkFever

1
이 일 전에

요한 복음 Zwinck의 대답, errno에 대한 배경 정보 용)

: http://www.gnu.org/software/libc/manual/html_node/Checking-for-Errors.html

가 특정의 errno WRT의 중요성에 정교하게하려면 읽기 : 모든 "오류"당신이했습니다 "의미하지 done something wrong "또는"이 연결을 읽을 수 없습니다 ". 예를 들어, errno가 논 블로킹 (non-blocking) 연결에서 EAGAIN 인 경우와 같이,이 순간에이 연결을 읽을 수 없다는 것을 의미 할 수도 있습니다.

즉 오류가 무엇인지 파악하고, 그 종류의 오류가 무엇인지 파악해야합니다. 그럼 당신은 예를 들어, 특히 errno에 대해 테스트 할 수 있습니다

#include <errno.h> 

int bytes = read(...); 
if (bytes == -1) { 
// example of an error which may happen under normal conditions 
// for certain kinds of file descriptors: 
    if (errno == EAGAIN) { 
     // handle appropriately 
    } else { 
     // this is a real error which should not happen 
    } 
} 

당신은 errno를의 int 값을 인쇄하고 errno.h 통해보고 상수를 찾을 수 있습니다. 실제로 /usr/include/asm-generic/errno.h 및 errno-base.h와 같이 errno.h에 포함 된 파일에 실제로 있습니다. 내 시스템 전에서 임의의 예 :

#define ECOMM 70 /* Communication error on send */

그래서 perror는() 또는 함수 strerror() 것 (아마도) 보고서 "전송에 통신 오류"하지만 어떤 경우에이의 int 값은 70이다 해당 코드를 코드에 사용하지 마십시오. 구현에 따라 다를 수 있습니다. #include <errno.h>이고 상수는 ECOMM입니다.

관련 문제