Is a serial port already open?

What C/C++ code is available to check if a serial port is already opened by another process / to prevent a port being opened by another process once it has been claimed by your own process? POSIX open() and related functions do not appear to supply this functionality.

I’ve got one solution here. It is simple and appears to work. Any comments - anything I’ve overlooked?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <limits.h>

#define MAX_LINE_LENGTH 200 /* arbitary limit */
static char buffer[ MAX_LINE_LENGTH ];

int main( int argc, char** argv )
int i;
int c;
FILE* f; /* popen() returns this /
Execute a command, creating a pipe to it for reading /
the output of the command into this process. /
if( ( f = popen(“sin fd | grep /dev/ser1” , “r” ) ) == NULL ) {
perror( “popen” );
Let’s look at what the command has sent to the pipe /
if ( fgets( buffer, MAX_LINE_LENGTH, f ) == NULL )
no output from the command /
fprintf( stderr, “\nNo open port /dev/ser1\n”);
else {
Read and display all the output lines from the command. /
The device could be already opened from several processes */
fputs( buffer, stdout );
while ( fgets( buffer, MAX_LINE_LENGTH, f ) != NULL) {
fputs( buffer, stdout );
pclose( f );