Skip to content

Commit a18ef1a

Browse files
Prevent changing port settings on already opened serial port on Linux using advisory locks, default serial ports to flow control off
1 parent 116a031 commit a18ef1a

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

serial_port/serial_port.cpp

+21-10
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,11 @@ serial_port::serial_port()
2323
/*-----------------------------------------------------*\
2424
| Set default port configuration but do not open |
2525
\*-----------------------------------------------------*/
26-
baud_rate = 9600;
27-
parity = SERIAL_PORT_PARITY_NONE;
28-
size = SERIAL_PORT_SIZE_8;
29-
stop_bits = SERIAL_PORT_STOP_BITS_1;
30-
flow_control = true;
26+
this->baud_rate = 9600;
27+
this->parity = SERIAL_PORT_PARITY_NONE;
28+
this->size = SERIAL_PORT_SIZE_8;
29+
this->stop_bits = SERIAL_PORT_STOP_BITS_1;
30+
this->flow_control = false;
3131
}
3232

3333
/*---------------------------------------------------------*\
@@ -40,11 +40,11 @@ serial_port::serial_port(const char * name, unsigned int baud)
4040
/*-----------------------------------------------------*\
4141
| Set default port configuration and open |
4242
\*-----------------------------------------------------*/
43-
baud_rate = baud;
44-
parity = SERIAL_PORT_PARITY_NONE;
45-
size = SERIAL_PORT_SIZE_8;
46-
stop_bits = SERIAL_PORT_STOP_BITS_1;
47-
flow_control = true;
43+
this->baud_rate = baud;
44+
this->parity = SERIAL_PORT_PARITY_NONE;
45+
this->size = SERIAL_PORT_SIZE_8;
46+
this->stop_bits = SERIAL_PORT_STOP_BITS_1;
47+
this->flow_control = false;
4848

4949
serial_open(name);
5050
}
@@ -230,6 +230,16 @@ bool serial_port::serial_open()
230230
return false;
231231
}
232232

233+
/*-----------------------------------------*\
234+
| Set an advisory lock on the port and |
235+
| abort port setup if already locked |
236+
\*-----------------------------------------*/
237+
if(flock(file_descriptor, LOCK_EX | LOCK_NB) < 0)
238+
{
239+
close(file_descriptor);
240+
return false;
241+
}
242+
233243
/*-----------------------------------------*\
234244
| Get the port configuration options |
235245
\*-----------------------------------------*/
@@ -496,6 +506,7 @@ void serial_port::serial_close()
496506
| Linux-specific code path for serial close |
497507
\*-----------------------------------------------------*/
498508
#ifdef __linux__
509+
flock(file_descriptor, LOCK_UN | LOCK_NB);
499510
close(file_descriptor);
500511
#endif
501512

serial_port/serial_port.h

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include <fcntl.h>
3232
#include <unistd.h>
3333
#include <termios.h>
34+
#include <sys/file.h>
3435
#include <sys/ioctl.h>
3536

3637
//these types are redefined in asm/termios.h

0 commit comments

Comments
 (0)