【发布时间】:2013-10-19 22:36:45
【问题描述】:
我想创建一个线程来等待来自文件描述符(串行端口)的数据。在那个时候我必须能够通过这个端口发送数据。
我尝试使用 pthread 和 poll,但程序从一开始就挂起(休眠),甚至不执行 main 函数中的第一个命令。
问题肯定在于轮询功能 - 当我限制时间时,所有指令都在此时间之后执行。
这是我的代码:
#define SERIAL_DEVICE "/dev/ttyUSB0"
#define SERIAL_BAUD 2400
#include <wiringSerial.h>
#include <stdio.h>
#include <pthread.h>
#include <poll.h>
//deklaracje
void *receiving( void *ptr )
{
printf("New thread started");
int fd= (int)ptr;
struct pollfd fds[1];
fds[0].fd = fd;
fds[0].events = POLLIN ;
int pollrc=-1;
while(1)
{
pollrc = poll( fds, 1, -1);
if (pollrc < 0)
{
perror("poll");
}
else if( pollrc > 0)
{
if( fds[0].revents & POLLIN )
{
unsigned char buff[1024];
ssize_t rc = read(fd, buff, sizeof(buff) );
if (rc > 0)
{
printf("RX: %s",buff);
}
}
}
}
}
int main(int argc, char *argv[])
{
int fd = serialOpen(SERIAL_DEVICE, SERIAL_BAUD);
if (fd<0)
{
printf("Serial opening error");
return 1;
}
pthread_t serialReceiver;
printf("-----");
int thr=pthread_create(&serialReceiver,NULL,receiving,fd);
printf("%i",thr);
if(thr!=0)
{
printf("Error during creating serialReceiver thread.");
return 1;
}
int status;
pthread_join(serialReceiver,(void **)&status);
printf("%i",status);
return 0;
}
【问题讨论】:
-
使用
poll时,不需要单独的线程。 -
给初学者的快速建议(可以是代码示例)。当我收到数据时触发操作的最佳方式是什么?我希望有机会在等待接收某些东西期间发送数据。正如你所注意到的,我将只使用一个 fd。
-
你不会知道那些 printf()s 对 main 函数的影响有多大。它们将缓冲输出,在它们被刷新之前你不会看到它。这发生在换行符(您的 printf()s 丢失)上,显式地使用 fflush() 或程序退出(这就是为什么您在添加超时时会看到一些东西)。
-
@Wojtek:什么会导致你发送数据?计时器?然后使用
poll超时(在主线程上),如果超时退出,则发送。在另一个 fd 上输入?然后将两个描述符都传递给poll,如果串口唤醒你就读取,如果另一个唤醒你就发送。 -
@AndreasBombe - 我的例子很好。当我向 printf 添加新行符号时,它按预期工作。谢谢。
标签: c linux multithreading file-descriptor