(root)/
strace-6.5/
tests/
pipe_maxfd.c
       1  /*
       2   * Copyright (c) 2016-2021 Dmitry V. Levin <ldv@strace.io>
       3   * All rights reserved.
       4   *
       5   * SPDX-License-Identifier: GPL-2.0-or-later
       6   */
       7  
       8  #include "tests.h"
       9  #include <limits.h>
      10  #include <unistd.h>
      11  #include <sys/resource.h>
      12  
      13  static void
      14  move_fd(int *from, int *to)
      15  {
      16  	for (; *to > *from; --*to) {
      17  		if (dup2(*from, *to) != *to)
      18  			continue;
      19  		close(*from);
      20  		*from = *to;
      21  		break;
      22  	}
      23  }
      24  
      25  void
      26  pipe_maxfd(int pipefd[2])
      27  {
      28  	struct rlimit rlim;
      29  	if (getrlimit(RLIMIT_NOFILE, &rlim))
      30  		perror_msg_and_fail("getrlimit");
      31  	if (rlim.rlim_cur < rlim.rlim_max) {
      32  		struct rlimit rlim_new;
      33  		rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
      34  		if (!setrlimit(RLIMIT_NOFILE, &rlim_new))
      35  			rlim.rlim_cur = rlim.rlim_max;
      36  	}
      37  
      38  	if (pipe(pipefd))
      39  		perror_msg_and_fail("pipe");
      40  
      41  	int max_fd = (rlim.rlim_cur > 0 && rlim.rlim_cur < INT_MAX)
      42  		     ? rlim.rlim_cur - 1 : INT_MAX;
      43  
      44  	move_fd(&pipefd[1], &max_fd);
      45  	--max_fd;
      46  	move_fd(&pipefd[0], &max_fd);
      47  }