I have created a c++ app that needs to connect to a modem via a serial port in order to give AT commands. I’ve followed the following answer: how to open, read, and write from serial port in C and it works great. In some point of the code it is mentioned that the working thread should sleep for enough time so that the sending and the reading of the characters to be consistent.
usleep ((7 + 25) * 100);
Since I’m not familiar enough with the linux system calls like usleep, I want to ask if this call is safe for the other linux processes that running in parallel with my program, or should I use the c++ default thread suspend execution method like std::this_thread::sleep_for?
In case I use usleep are there things that I should watch for?
Advertisement
Answer
The only thing you should watch for is that this won’t work on windows (there is no usleep function as usleep is os-specific). Probably the code that you mentioned in your post is old and pre-C++11 standard. Before C++11 there was no standard thread library so people has to use os-specific things.
If you have a C++11 (which on linux should be true) then you can use this portable version (if you don’t plan on running this code on windows it doesn’t matter probably):
#include <chrono> #include <thread> ... std::this_thread::sleep_for(std::chrono::microseconds(usec));
There is no way to answer if this is safe to other processes. I can’t see the code for your program. It might be safe it might be not it depends on what you are doing and who else would read or write something to serial port.