简体   繁体   English

Linux-使用互斥锁同步串行端口

[英]Linux - Using mutex to synchonise serial port

I'm writing a C program for Linux OS. 我正在为Linux操作系统编写C程序。
The program can start a timer: both main program and timer can send and receive characters on a serial port. 该程序可以启动一个计时器:主程序和计时器都可以在串行端口上发送和接收字符。
My attempt is to serialize the serial port access by a mutex in a global structure initialized on the opening with: 我的尝试是通过在开头用以下内容初始化的全局结构中的互斥锁来序列化串行端口访问:

if (pthread_mutex_init( &pED->lockSerial, NULL) != 0)
{   
    lwsl_err("lockSerial init failed\n");
}

I protected all the functions that send data on the port as follow: 我保护了在端口上发送数据的所有功能,如下所示:

ssize_t cmdFirmwareVersion(EngineData *pED)
{
  if (pED->fdSerialPort==-1)
    return -1;

  LOCK_SERIAL;
  unsigned char cmd[] = { 0x00, 0x00, 0x7F };
  write( pED->fdSerialPort, cmd, sizeof(cmd));
  int rx = read ( pED->fdSerialPort, rxbuffer, sizeof rxbuffer);
  dump( rxbuffer, rx);
  UNLOCK_SERIAL;
  return rx;
}

where 哪里

#define LOCK_SERIAL if (0!=pthread_mutex_lock(&pED->lockSerial)) {printf("Err lock");return 0;}
#define UNLOCK_SERIAL   pthread_mutex_unlock(&pED->lockSerial);

Running the program and starting the timer I see the requests are regular. 运行程序并启动计时器,我看到请求是正常的。 When I trigger one of this calls on other way (from a rx websocket function) the program hangs and I need to kill it. 当我以其他方式(从rx websocket函数)触发此调用之一时,程序挂起,我需要将其杀死。

Why the entire program stops ?? 为什么整个程序停止?

If a process hangs, it could be because of circular wait for mutexes or holding mutex and trying to lock it again. 如果进程挂起,则可能是因为循环等待互斥锁或保持互斥锁并尝试再次锁定它。 This could cause deadlock. 这可能会导致死锁。

ps output will show thread's state as D or S if it's waiting for a resource. ps输出将在等待资源时将其状态显示为D或S。 it will appear as the process is hung. 进程挂起时,它将出现。

               D    uninterruptible sleep (usually IO)
               S    interruptible sleep (waiting for an event to complete)

I have made a thread to hold mutex and try to lock it again. 我做了一个线程来保存互斥锁,然后尝试再次锁定它。 ps output and GDB shows main thread and child thread are in sleep. ps输出和GDB显示主线程和子线程处于睡眠状态。

xxxx@virtualBox:~$ ps -eflT |grep a.out
0 S root      3982  3982  2265  0  80   0 - 22155 -      20:28 pts/0    00:00:00 ./a.out
1 S root      3982  3984  2265  0  80   0 - 22155 -      20:28 pts/0    00:00:00 ./a.out

(gdb) info threads 
  Id   Target Id         Frame 
* 1    Thread 0x7ffff7fdf740 (LWP 4625) "a.out" 0x00007ffff7bbed2d in     __GI___pthread_timedjoin_ex (
    threadid=140737345505024, thread_return=0x0, abstime=0x0, block=    <optimized out>) at pthread_join_common.c:89
  2    Thread 0x7ffff77c4700 (LWP 4629) "a.out" __lll_lock_wait ()
    at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135

Please check blog Tech Easy for more information on threads. 请查看博客Tech Easy以获取有关线程的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM