I'm implementing a simple protocol to do file transfer between 2 PC's over serial port and I'm getting a weird error.
On the main I call a function "llopen":
int
llopen(int port, int type) {
int fd = 0;
char* PORT;
PORT = malloc( sizeof(char) * (strlen(COM) + 1) );
sprintf(PORT,"%s%d",COM,port);
fd = initialization(PORT); // Open(...): returns a file descriptor!
switch(type) {
case SENDER:
return connectSender(fd);
break;
case RECEIVER:
return connectReceiver(fd);
break;
}
return fd; // The fd value here is 5
}
After that, I call a function llwrite(int fd, ...) to write a string to the file descriptor, but I'm getting an error: "Bad file descriptor" on llwrite(int fd, ...). If I call again the initialization(port) function, before that, it works and it writes the N bytes on the file descriptor, but if I don't it gives to me the "Bad file descriptor" error again.
Here it is the llwrite(int fd, ...) function:
int
llwrite(int fileDescriptor, unsigned char* buffer, unsigned int length) {
// The fd value here is 5
return writeBuffer(fileDescriptor,buffer,length);
}
Even before the return statement if I call, for instance, the tcflush(...) function I'm getting the "Bad file descriptor" error.
Any clue? Thanks in advance!
EDIT:
The problem is solved.
llopen(...) was wrong. I was returning the number of bytes wrote on the ConnectReceiver(...) / ConnectSender(...) and not the file descriptor
Now it's right:
int
llopen(int port, int type) {
int fd = 0;
char* PORT;
PORT = malloc( sizeof(char) * (strlen(COM) + 1) );
sprintf(PORT,"%s%d",COM,port);
fd = initialization(PORT); // Open(...): returns a file descriptor!
switch(type) {
case SENDER:
if( connectSender(fd) > 0 ) return fd;
case RECEIVER:
if( connectReceiver(fd) > 0 ) return fd;
}
return -1;
}
\\.\COM1
(beware of escaping the backslashes properly...) – Adrien Plisson