我想在主程序中退出时把线程也终止了,有什么办法?
不退出读串口中的read()好像会造成堵塞。
代码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <strings.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include <signal.h>
#define BAUDRATE B115200            
#define MODEMDEVICE "/dev/ttySAC0"
#define _POSIX_SOURCE 1 
#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE; 
static int QUIT=FALSE; 
void *myThread(void)
{
    int fd,res;
    struct termios oldtio,newtio;
    char buf[255];
    fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY ); 
    if (fd <0) {perror(MODEMDEVICE); exit(-1); }
    tcgetattr(fd,&oldtio); 
    bzero(&newtio, sizeof(newtio)); 
    newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
    newtio.c_iflag = IGNPAR;
    newtio.c_oflag = 0;
    newtio.c_lflag = 0;
     newtio.c_cc[VTIME] = 0;   
    newtio.c_cc[VMIN] = 5;  
    tcflush(fd, TCIFLUSH);
    tcsetattr(fd,TCSANOW,&newtio);
    //pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    //pthread_setcanceltype(PTHREAD_CANCEL_ASYCHRONOUS, NULL);
    while (STOP==FALSE) 
    {    
        pthread_testcancel(); 
        res = read(fd,buf,255); 
        pthread_testcancel(); 
        buf[res]=0;
        printf(":%s:%d\n", buf, res);
        if (buf[0]=='z') STOP=TRUE;
    }
     tcsetattr(fd,TCSANOW,&oldtio);
}
int main()
{
    int ret;
    pthread_t tid;
    ret = pthread_create(&tid, NULL, (void*)myThread, NULL);
    if (ret)
    {
        printf("pthread error!\n");
        return 1;
    }
    sleep(10);
}