1// SPDX-License-Identifier: GPL-2.0-or-later 2/* 3 * Copyright (c) 2020 Francis Laniel. All rights reserved. 4 * Author: Francis Laniel <laniel_francis@privacyrequired.com> 5 * 6 * Test Description: 7 * This Program tests getting and setting the pipe size. 8 * It also tests what happen when you write to a full pipe depending on whether 9 * O_NONBLOCK is set or not. 10 */ 11#define _GNU_SOURCE 12#include <stdlib.h> 13#include <features.h> 14#include <unistd.h> 15#include <stdio.h> 16#include "lapi/fcntl.h" 17#include "tst_test.h" 18 19static int fds[2]; 20static int flags; 21 22static void test_pipe2(void) 23{ 24 int ret; 25 pid_t pid; 26 27 /* 28 * This ensures parent process is still in non-block mode when 29 * using -i parameter. Subquent writes hould return -1 and errno 30 * set to either EAGAIN or EWOULDBLOCK because pipe is already full. 31 */ 32 SAFE_FCNTL(fds[1], F_SETFL, flags | O_NONBLOCK); 33 ret = write(fds[1], "x", 1); 34 if (ret == -1) { 35 if (errno == EAGAIN) 36 tst_res(TPASS | TERRNO, "write failed as expected"); 37 else 38 tst_brk(TFAIL | TERRNO, "write failed expected EAGAIN but got"); 39 } else { 40 tst_res(TFAIL, "write() succeeded unexpectedly"); 41 } 42 43 pid = SAFE_FORK(); 44 if (!pid) { 45 SAFE_FCNTL(fds[1], F_SETFL, flags & ~O_NONBLOCK); 46 SAFE_WRITE(SAFE_WRITE_ALL, fds[1], "x", 1); 47 } 48 49 if (TST_PROCESS_STATE_WAIT(pid, 'S', 1000) < 0) 50 tst_res(TFAIL, "Child process is not blocked"); 51 else 52 tst_res(TPASS, "Child process is blocked"); 53 54 SAFE_KILL(pid, SIGKILL); 55 SAFE_WAIT(NULL); 56} 57 58static void setup(void) 59{ 60 int page_size, pipe_size; 61 char *write_buffer; 62 63 SAFE_PIPE2(fds, O_NONBLOCK); 64 page_size = SAFE_SYSCONF(_SC_PAGESIZE); 65 66 flags = SAFE_FCNTL(fds[1], F_GETFL); 67 if (!(flags & O_NONBLOCK)) 68 tst_brk(TCONF, "O_NONBLOCK flag must be set"); 69 /* 70 * A pipe has two file descriptors. 71 * But in the kernel these two file descriptors point to the same pipe. 72 * So setting size from first file handle set size for the pipe. 73 */ 74 SAFE_FCNTL(fds[0], F_SETPIPE_SZ, 0); 75 76 /* 77 * So getting size from the second file descriptor return the size of 78 * the pipe which was changed before with first file descriptor. 79 */ 80 pipe_size = SAFE_FCNTL(fds[1], F_GETPIPE_SZ); 81 if (pipe_size != page_size) 82 tst_res(TFAIL, "Pipe size (%d) must be page size (%d)", 83 pipe_size, page_size); 84 85 write_buffer = SAFE_MALLOC(pipe_size); 86 memset(write_buffer, 'x', pipe_size); 87 SAFE_WRITE(SAFE_WRITE_ALL, fds[1], write_buffer, pipe_size); 88 free(write_buffer); 89} 90 91static void cleanup(void) 92{ 93 if (fds[0] > 0) 94 SAFE_CLOSE(fds[0]); 95 if (fds[1] > 0) 96 SAFE_CLOSE(fds[1]); 97} 98 99static struct tst_test test = { 100 .test_all = test_pipe2, 101 .setup = setup, 102 .cleanup = cleanup, 103 .forks_child = 1, 104}; 105