1// SPDX-License-Identifier: GPL-2.0-or-later 2/* 3 * Copyright (c) 2021 FUJITSU LIMITED. All rights reserved. 4 * Author: Yang Xu <xuyang2018.jy@fujitsu.com> 5 */ 6 7/*\ 8 * [Description] 9 * 10 * Test whether the file offset are the same for both file descriptors. 11 */ 12 13#include <errno.h> 14#include <stdio.h> 15#include <unistd.h> 16#include "tst_test.h" 17#include "tst_safe_macros.h" 18 19#define WRITE_STR "abcdefg" 20 21static int ofd = -1, nfd = 10; 22 23static struct tcase { 24 off_t offset; 25 size_t exp_size; 26 /* 0 - change offset before dup2, 1 - change offset after dup2 */ 27 int flag; 28 char *exp_data; 29 char *desc; 30} tcases[] = { 31 {1, 6, 0, "bcdefg", "Test offset with lseek before dup2"}, 32 {2, 5, 1, "cdefg", "Test offset with lseek after dup2"}, 33}; 34 35static void setup(void) 36{ 37 ofd = SAFE_OPEN("testfile", O_RDWR | O_CREAT, 0644); 38 SAFE_WRITE(SAFE_WRITE_ALL, ofd, WRITE_STR, sizeof(WRITE_STR) - 1); 39} 40 41static void cleanup(void) 42{ 43 if (ofd > 0) 44 SAFE_CLOSE(ofd); 45 close(nfd); 46} 47 48static void run(unsigned int i) 49{ 50 struct tcase *tc = tcases + i; 51 char read_buf[20]; 52 53 memset(read_buf, 0, sizeof(read_buf)); 54 55 tst_res(TINFO, "%s", tc->desc); 56 if (!tc->flag) 57 SAFE_LSEEK(ofd, tc->offset, SEEK_SET); 58 59 TEST(dup2(ofd, nfd)); 60 if (TST_RET == -1) { 61 tst_res(TFAIL | TTERRNO, "call failed unexpectedly"); 62 return; 63 } 64 if (tc->flag) 65 SAFE_LSEEK(ofd, tc->offset, SEEK_SET); 66 67 SAFE_READ(1, nfd, read_buf, tc->exp_size); 68 if (strncmp(read_buf, tc->exp_data, tc->exp_size)) 69 tst_res(TFAIL, "Expect %s, but get %s.", tc->exp_data, read_buf); 70 else 71 tst_res(TPASS, "Get expected buf %s", read_buf); 72} 73 74static struct tst_test test = { 75 .needs_tmpdir = 1, 76 .tcnt = ARRAY_SIZE(tcases), 77 .test = run, 78 .setup = setup, 79 .cleanup = cleanup, 80}; 81