Answer the question
In order to leave comments, you need to log in
How to create read and write streams for a socket?
You have to write in c++. In java, everything is easier, maybe I'm trying to use the same approach or there is not enough knowledge in c++. Generally it is necessary to make 2 flows. One for reading from the socket, the other for writing to it. Queue is my implementation of queue with mutexes for thread-safe access. The problem is that I don't understand how to do it. The catch is that pthread_create needs static methods, but both readCan and writeCan cannot be static.
//Can.h
class Can {
private:
int sockfd; /* can raw socket */
char *interface_name = "can0";
struct sockaddr_can addr;
pthread_t readThread;
pthread_t writeThread;
static Queue<can_frame> acceptQueue;
static Queue<can_frame> sendQueue;
static bool threadSign;
static void *runnerRead(void*);
static void *runnerWrite(void*);
bool openCan();
bool startThreads();
protected:
bool writeCan(msghdr msg);
bool writeCan(can_frame frame);
can_frame readCan();
public:
Can();
bool start();
void send(can_frame frame);
can_frame accept();
bool upCanInterface();
bool downCanInterface();
void closeCan();
};
//Can.cpp
void Can::send(can_frame frame) {
sendQueue.push(frame);
}
can_frame Can::accept() {
return acceptQueue.pop();
}
bool Can::writeCan(can_frame frame) {
if(sockfd <= 0) {
std::cout << "ERROR: " << "Can't write to CAN socket (sockfd = " << sockfd << ")" << std::endl;
return false;
}
if(write(sockfd, &frame, CAN_MTU) != CAN_MTU) {
std::cout << "ERROR: " << "Can't write to CAN socket (write() return value < 0)" << strerror(errno) << std::endl;
return false;
}
return true;
}
can_frame Can::readCan() {
can_frame frame;//test
return frame;
}
bool Can::startThreads() {
if(pthread_create( &readThread, NULL, &runnerRead, NULL )) {
std::cout << "ERROR: " << "Can't start read thread CAN" << std::endl;
return false;
}
if(pthread_create( &writeThread, NULL, &runnerWrite, NULL )) {
std::cout << "ERROR: " << "Can't start write thread CAN" << std::endl;
return false;
}
return true;
}
void *Can::runnerRead(void*) {
while(threadSign) {
acceptQueue.push(readCan());
}
}
void *Can::runnerWrite(void*) {
while(threadSign) {
writeCan(sendQueue.pop());
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question