Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 158717
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T10:43:51+00:00 2026-05-11T10:43:51+00:00

I wrote a simple program that reads the characters from external device (bar code

  • 0

I wrote a simple program that reads the characters from external device (bar code scanner) from serial port (/dev/ttyS1) and feeds it to the currently active window (using XSendEvent).

Program works fine on faster computers, but on slow ones the situation happens (very often) that characters don’t get received in the same order they were sent. For example, scanner sends 1234567 to serial port, my program sends char events 1234567, but the active program (xterm for example) receives 3127456. I tried calling XSync in various places and adding usleep calls, but it did not help.

Does anyone have an idea how to force the ‘order’ of characters?

Or is there some other way to send a string to the active window (I don’t even mind using an external program if needed)?

Here’s the code, perhaps I’m just doing something wrong:

#include <stdio.h> #include <stdlib.h> #include <termios.h> #include <unistd.h> #include <errno.h> #include <sys/types.h>  // serial port stuff #include <sys/stat.h> #include <string.h> #include <fcntl.h> #include <X11/Xlib.h>  /*     BarCode KeyboardFeeder: BCKF     Copyright (c) Milan Babuskov     Licence: GNU General Public Licence      Compile with: g++ bckf.cpp -lX11 -L /usr/X11R6/lib/ -o bckf     Keycodes:  /usr/X11R6/include/X11/keysymdef.h */ //----------------------------------------------------------------------------- void SendEvent(XKeyEvent *event, bool press) {     if (press)         XSendEvent(event->display, event->window, True, KeyPressMask, (XEvent *)event);     else         XSendEvent(event->display, event->window, True, KeyReleaseMask, (XEvent *)event);     XSync(event->display, False); } //----------------------------------------------------------------------------- bool sendChar(int c) {     if (c >= 0x08 && c <= 0x1b)     // send CR twice     {         sendChar(0xff0d);         c = 0xff0d;     }      printf('Sending char : 0x%02x\n', c);     char disp[] = ':0';     char *dp = getenv('DISPLAY');     if (!dp)         dp = disp;     else         printf('Using env.variable $DISPLAY = %s.\n', dp);     Display *dpy = XOpenDisplay(dp);     if (dpy == NULL)     {         printf('ERROR! Couldn't connect to display %s.\n', dp);         return false;     }     else     {         Window cur_focus;   // focused window         int revert_to;      // focus state         XGetInputFocus(dpy, &cur_focus, &revert_to);    // get window with focus         if (cur_focus == None)         {             printf('WARNING! No window is focused\n');             return true;         }         else         {             XKeyEvent event;             event.display = dpy;             event.window = cur_focus;             event.root = RootWindow(event.display, DefaultScreen(event.display));             event.subwindow = None;             event.time = CurrentTime;             event.x = 1;             event.y = 1;             event.x_root = 1;             event.y_root = 1;             event.same_screen = True;             event.type = KeyPress;             event.state = 0;             event.keycode = XKeysymToKeycode(dpy, c);             SendEvent(&event, true);             event.type = KeyRelease;             SendEvent(&event, false);         }         XCloseDisplay(dpy);     }      usleep(20);     return true; } //----------------------------------------------------------------------------- // Forward declaration int InitComPort(const char *port); //----------------------------------------------------------------------------- int main(int argc, char **argv) {     if (argc != 2)     {         printf('Usage: bckf serial_port\n');         return 1;     }      int port = InitComPort(argv[1]);     if (port == -1)         return 1;      while (true)     {         char buf[30];         ssize_t res = read(port, buf, 30);         if (res > 0)         {             for (ssize_t i=0; i<res; ++i)             {                 int c = buf[i];                 printf('Received char: 0x%02x\n', c);                 if (c >= '0' && c <= '9' || c >= 0x08 && c <= 0x1b)                     if (!sendChar(c))   // called from console?                         break;             }         }     }     return 0; } //----------------------------------------------------------------------------- int InitComPort(const char *port) {     int c, res;     struct termios newtio;     struct termios oldtio;      // Open modem device for reading and writing and not as controlling tty     // because we don't want to get killed if linenoise sends CTRL-C.     int fdSerial = open(port, O_RDWR | O_NOCTTY );     if (fdSerial < 0)     {         printf(0, 'Error opening port: %s\n%s', port, strerror(errno));         return -1;     }      tcgetattr(fdSerial,&oldtio); // save current port settings     memset(&newtio, 0, sizeof(newtio));     newtio.c_cflag = B9600 | CS8 | CLOCAL | CREAD;                  // CREAD   : enable receiving characters                                                                     // CS8     : character size 8                                                                     // CLOCAL  : Ignore modem control lines     newtio.c_iflag = IGNPAR;                                        // IGNPAR  : ignore bytes with parity errors     newtio.c_oflag = 0;                                             // 0       : raw output (no echo, non-canonical)     //newtio.c_cc[VTIME]    = timeout;                              // 10=1sec : inter-character timer (deciseconds)     newtio.c_cc[VMIN]     = 1;                                      // 50      : blocking read until 50 chars received     tcflush(fdSerial, TCIOFLUSH);                                   // clear the line and...     tcsetattr(fdSerial,TCSANOW,&newtio);                            // ...activate new settings for the port     return fdSerial; } //----------------------------------------------------------------------------- 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T10:43:52+00:00Added an answer on May 11, 2026 at 10:43 am

    the problem in your code is that you open the display every time with XOpenDisplay(…). Every call to XOpenDisplay creates a new protocol context. You should open the display only once, and always use the same display handle when you send the events. Within the context of a single display handle, the events are guaranteed to remain ordered.

    Initialize the display once, e.g. in main(…), before you start to call sendChar(…), and always use the same Display pointer. Close the Display only when you are done, like you do with the Com port.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 175k
  • Answers 175k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Any expression in SQL must reference columns only in one… May 12, 2026 at 3:06 pm
  • Editorial Team
    Editorial Team added an answer .gitignore will only ignore files not already checked in. In… May 12, 2026 at 3:06 pm
  • Editorial Team
    Editorial Team added an answer I think you are looking for ResourceSet.createResource(URI uri, String contentType).… May 12, 2026 at 3:06 pm

Related Questions

I have a PHP script (running on a Linux server) that ouputs the names
I am trying to read values from an input file in Perl. Input file
My program generates relatively simple PDF documents on request, but I'm having trouble with
I'm trying to write a program that takes input of - hexadecimals, octals, and

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.