Advertisement
Marionumber1

Message-based file I/O

Jun 8th, 2014
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. /* Create an unnamed message queue for replies to I/O requests */
  2. mqueue_t *io_reply_queue = mqueue_create(NULL);
  3.  
  4. /* Open the file */
  5. file_t *notes = file_open("~/Documents/notes.txt", FILE_READ);
  6.  
  7. /* Issue multiple asynchronous read requests, with request identifiers */
  8. char buffer1[512], buffer2[512];
  9. file_read_async(notes, buffer1, 0, 512, io_reply_queue, 0);
  10. file_read_async(notes, buffer2, 512, 512, io_reply_queue, 1);
  11.  
  12. /* Number of writes completed */
  13. int num_writes_done = 0;
  14.  
  15. /* Wait for responses */
  16. while(1)
  17. {
  18.     /* Block for replies */
  19.     message_t *msg = mqueue_recv(io_reply_queue);
  20.  
  21.     /* Which type of operation completed? */
  22.     switch(msg->method)
  23.     {
  24.     case FILE_READ_FINISH:
  25.         /* Read failed */
  26.         if (msg->reply < 0)
  27.         {
  28.             printf("Read failed\n");
  29.             return 1;
  30.         }
  31.  
  32.         /* First read request */
  33.         switch(msg->id)
  34.         {
  35.         case 0:
  36.             buffer1[0] = 'A';
  37.             file_write_async(notes, buffer1, 0, 512, io_reply_queue, 0);
  38.             break;
  39.         case 1:
  40.             buffer2[0] = 'B';
  41.             file_write_async(notes, buffer2, 512, 512, io_reply_queue, 1);
  42.             break;
  43.         default:
  44.             printf("Invalid read reply\n");
  45.             return 1;
  46.         }
  47.  
  48.         break;
  49.     case FILE_WRITE_FINISH:
  50.         /* Write failed */
  51.         if (msg->reply < 0)
  52.         {
  53.             printf("Write failed\n");
  54.             return 1;
  55.         }
  56.  
  57.         /* One more write finished */
  58.         num_writes_done++;
  59.         if (num_writes_done == 2)
  60.         {
  61.             printf("Done\n");
  62.             return 0;
  63.         }
  64.  
  65.         break;
  66.     default:
  67.         printf("Invalid message\n");
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement