Reading /(Writing) Data from / (to) a Descriptor (Dispatch Sources)

来源:互联网 发布:sql判断字段是否为空 编辑:程序博客网 时间:2024/06/05 18:09
// Read
dispatch_source_t ProcessContentsOfFile(const char* filename)  {     // Prepare the file for reading.     int fd = open(filename, O_RDONLY);     if (fd == -1)        return NULL;     fcntl(fd, F_SETFL, O_NONBLOCK);  // Avoid blocking the read operation     dispatch_queue_t queue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);dispatch_source_t readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, queue);     if (!readSource)     {close(fd);        return NULL;     }     // Install the event handler     dispatch_source_set_event_handler(readSource, ^{        size_t estimated = dispatch_source_get_data(readSource) + 1;        // Read the data into a text buffer.        char* buffer = (char*)malloc(estimated);        if (buffer)        {           ssize_t actual = read(fd, buffer, (estimated));           Boolean done = MyProcessFileData(buffer, actual);  // Process the data.// Release the buffer when done.           free(buffer);           // If there is no more data, cancel the source.           if (done)              dispatch_source_cancel(readSource);        }});     // Install the cancellation handler     dispatch_source_set_cancel_handler(readSource, ^{close(fd);});     // Start reading the file.     dispatch_resume(readSource);     return readSource;}
</pre><pre name="code" class="objc">
// Write
</pre><pre name="code" class="objc"><pre name="code" class="objc">dispatch_source_t WriteDataToFile(const char* filename)  {      int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC,                        (S_IRUSR | S_IWUSR | S_ISUID | S_ISGID));      if (fd == -1)          return NULL;      fcntl(fd, F_SETFL); // Block during the write.      dispatch_queue_t queue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);      dispatch_source_t writeSource =  dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE,if (!writeSource){close(fd);    return NULL;}fd, 0, queue);dispatch_source_set_event_handler(writeSource, ^{    size_t bufferSize = MyGetDataSize();    void* buffer = malloc(bufferSize);    size_t actual = MyGetData(buffer, bufferSize);    write(fd, buffer, actual);free(buffer);          // Cancel and release the dispatch source when done.          dispatch_source_cancel(writeSource);      });      dispatch_source_set_cancel_handler(writeSource, ^{close(fd);});      dispatch_resume(writeSource);      return (writeSource);}


                                             
0 0
原创粉丝点击