Search code examples
linuxpipelimitulimit

Max number of open files per process in Linux


I using the command: ulimit -n and i take the number 1024, which is the max number of open files per process in my system. But with the following programm i take the number 510...? What is wrong

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <errno.h>


    int main( void )

{
        int pipe_ext = 0, pfd[ 2 ], counter = 0;

        while ( 1 )
        {
                pipe_ext = pipe( pfd );
                //errno = 0;

                if ( pipe_ext == 0 )
                {
                        write( pfd[ 1 ], "R", 1 );

                        counter = counter + 1;
                        printf("Counter = %d\n", counter );
                }
                else
                {
                        perror( "pipe()" );
                        printf("errno = %d\n", errno );
                        exit( 1 );
                }

        }

        return( 0 );
}

Solution

  • There is no issue here.

    A pipe has two ends, each gets its own file descriptor.

    So, each end of a pipe counts as a file against the limit.

    The slight difference between 1024/2 = 512 and 510 is because your process has already opened the files stdin, stdout, and stderr, which counts against the limit.