2015年2月2日 星期一

[C] CreateThreadL - fifopath

#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <pthread.h>

const char* fifopath = "./mkfifo.file";
pthread_t threadid;

// thread entry point
void* FifoWriterThread(void* arg)
{
   const char* buf = "somejunk";
   int fd = open (fifopath, O_WRONLY);
   if(fd > 0 )
   {
      write(fd, buf, 9);     
      close(fd);
   }
   return 0;
}

void CreateThreadL()
{
   pthread_create(&threadid,NULL,FifoWriterThread, NULL);
}

void OpenForRead()
{
   int err = mkfifo (fifopath, 0666);
   if(err != 0)
   {
       // probably file already exists, delete the file
       unlink(fifopath); 
       // try once more..
       err = mkfifo (fifopath, 0666);
       if(err != 0)
       {
            return;
       }
   }
   CreateThreadL();
   char buf[128];
   int fd = open (fifopath, O_RDONLY);
   if ( fd == 0 )
       {
           return ;
       }
   err = read (fd, buf, 128);  

   printf("string = %s   String length = %d\n ",buf,(err-1)); /* err -1 = remove \n*/
   close(fd);   
   unlink(fifopath);
}    

int main()
{
   OpenForRead();
   return 0;
}


Compiler C code
gcc -pthread happy.c -o happy


Reference:
Named Pipes Example

0 意見:

張貼留言