I am getting a SIGPIPE error when I try to write to a file descriptor that was returned when I opened a USB device. I can read all day from it, but I cannot write to it. Below is the code:
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <sys/socket.h>
#include <string>
#include <stdio.h>
#include <sstream>
#include <pthread.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
void* Thread(void*);
int fd = -1;
std::string masterName;
std::string slavename;
int main() {
char buf[1024];
fd = open("/dev/usbdevice", O_RDWR | O_NOCTTY);
pthread_t thread;
pthread_create(&thread, NULL, Thread, (void*)NULL);
while(1) {
int returnVal = read(fd, buf, sizeof(buf));
if(returnVal <= 0) {
std::cout << "Read() returned 0 bytes." << std::endl;
break;
}
std::cout << "Buffer Data: " << byteChars << std::endl;
}
close(fd);
return 0;
}
void* Thread(void*) {
char buffer[2];
while(1) {
memset(buffer, 0, 2);
std::cout << "Write to device: " << std::endl;
std::cin >> buffer;
ssize_t ret = write(fd, buffer, 2);
if(ret == -1) {
std::cout << "errno: " << errno << std::endl;
}
else {
std::cout << "Successful write" << std::endl;
}
}
return NULL;
}
Basically I set up a thread to be able to write to the file descriptor "fd" of which was returned from the "open()" function in the beginning. I get an error every time I attempt to write to it. But as I said before, I can read from it all day with no problem.
Side Note I have checked the fd to make sure I am writing to the correct one and I definitely am.
When I researched the SIGPIPE error, I see that every one says it happens when the fd gets closed on the remote end. So #1 how is it possible for that file descriptor to get closed? And #2 how am I still able to read from the device on the same file descriptor if it is closed?