Back to home page

LXR

 
 

    


File indexing completed on 2025-05-11 08:24:18

0001 /**
0002  * @file
0003  *
0004  * @ingroup FIFO_PIPE
0005  *
0006  * @brief Create an Anonymous Pipe
0007  */
0008 
0009 /*
0010  * Author: Wei Shen <cquark@gmail.com>
0011  *
0012  * The license and distribution terms for this file may be
0013  * found in the file LICENSE in this distribution or at
0014  * http://www.rtems.org/license/LICENSE.
0015  */
0016 
0017 #ifdef HAVE_CONFIG_H
0018 #include "config.h"
0019 #endif
0020 
0021 #include <stdio.h>
0022 #include <string.h>
0023 #include <fcntl.h>
0024 #include <rtems/libio_.h>
0025 #include <rtems/seterr.h>
0026 #include <rtems/pipe.h>
0027 
0028 /* Incremental number added to names of anonymous pipe files */
0029 /* FIXME: This approach is questionable */
0030 static uint16_t rtems_pipe_no = 0;
0031 
0032 int pipe(
0033   int filsdes[2]
0034 )
0035 {
0036   rtems_libio_t *iop;
0037   int err = 0;
0038 
0039   if (filsdes == NULL)
0040     rtems_set_errno_and_return_minus_one( EFAULT );
0041 
0042   if (rtems_mkdir("/tmp", S_IRWXU | S_IRWXG | S_IRWXO) != 0)
0043     return -1;
0044 
0045   /* /tmp/.fifoXXXX */
0046   char fifopath[15];
0047   memcpy(fifopath, "/tmp/.fifo", 10);
0048   sprintf(fifopath + 10, "%04x", rtems_pipe_no ++);
0049 
0050   /* Try creating FIFO file until find an available file name */
0051   while (mkfifo(fifopath, S_IRUSR|S_IWUSR) != 0) {
0052     if (errno != EEXIST){
0053       return -1;
0054     }
0055     /* Just try once... */
0056     return -1;
0057     /* sprintf(fifopath + 10, "%04x", rtems_pipe_no ++); */
0058   }
0059 
0060   /* Non-blocking open to avoid waiting for writers */
0061   filsdes[0] = open(fifopath, O_RDONLY | O_NONBLOCK);
0062   if (filsdes[0] < 0) {
0063     err = errno;
0064     /* Delete file at errors, or else if pipe is successfully created
0065      the file node will be deleted after it is closed by all. */
0066     unlink(fifopath);
0067   }
0068   else {
0069   /* Reset open file to blocking mode */
0070     iop = rtems_libio_iop(filsdes[0]);
0071     rtems_libio_iop_flags_clear( iop, LIBIO_FLAGS_NO_DELAY );
0072 
0073     filsdes[1] = open(fifopath, O_WRONLY);
0074 
0075     if (filsdes[1] < 0) {
0076     err = errno;
0077     close(filsdes[0]);
0078     }
0079   unlink(fifopath);
0080   }
0081   if(err != 0)
0082     rtems_set_errno_and_return_minus_one(err);
0083   return 0;
0084 }
0085