Skip to content

Notes On Linux C Programming

September 19, 2014

Pthread

General

  1. Include file : pthread.h
  2. Link library: libpthread

Function Implementation

#define NULL_1  NULL
 #define NULL_2  NULL
 static void* ThreadSPIRead(void *dummy)
 {
     //thread processing
     while(1) {};

     exit(EXIT_SUCCESS);
 }

 int main(void)
 {
     int ret;
     pthread_t fdThread;
     void *thread_return;

     ret = pthread_create(&fdThread, NULL_1, ThreadSPIRead, NULL_2);
     if(ret < 0)
         ErrorAbort("Error create SPI thread\n");
     //waiting thread to exit
     ret = pthread_join(fdThread, &thread_return);
 }
  1. NULL_1 : thread related attribute : eg stack size,scheduling policy
  2. NULL_2 : parameter into thread, here is none

Named Pipe

int main(void)
{
    int ret;
    char *FIFO_NAMED = "/tmp/spi_drv1";

    /* create the FIFO (named pipe) */
    mkfifo(FIFO_NAMED, 0666|S_IFIFO|S_IRUSR| S_IWUSR);
    /* open the FIFO (named pipe) */
    fdSPIFifo = open(FIFO_NAMED, O_RDWR);
    //fdSPIFifo = open(FIFO_NAMED, O_RDONLY|O_NONBLOCK); //default is blocking open
    if (fdSPIFifo < 0)
       ErrorAbort("spi_drv:Error simulate spi device\n");
    /* write to the FIFO (named pipe) */
    write(fd, "Hi", sizeof("Hi"));

    /* close to the FIFO (named pipe) */
    close(fd);
    /* remove the FIFO */
    unlink(FIFO_NAMED); 
}

/*fifo reading
static void* ThreadSPIRead(void *dummy)
{
    unsigned char buf[FIFO_DATA_LEN*2];
    int len;
    int index=0;

    while(!threadExit)
    {
        len = read(fdSPIFifo, &buf[index], FIFO_DATA_LEN);
        if(len < 0)
        {
            printf("something went wrong with read()! %s\n", strerror(errno));
            usleep(100000); //sleep 100ms
            continue;
         }
         //processing received data from named pipe
     }
  }
Advertisements

From → Embedded Linux

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: