Zi Lin | 171ee1e | 2021-10-13 03:12:18 +0000 | [diff] [blame^] | 1 | /* Copyright 2021 The Chromium OS Authors. All rights reserved. |
| 2 | * Use of this source code is governed by a BSD-style license that can be |
| 3 | * found in the LICENSE file. |
| 4 | */ |
| 5 | |
| 6 | #include "test_util.h" |
| 7 | |
| 8 | #include <stdio.h> |
| 9 | #include <stdlib.h> |
| 10 | #include <string.h> |
| 11 | #include <unistd.h> |
| 12 | |
| 13 | #include "util.h" |
| 14 | |
| 15 | #define MAX_PIPE_CAPACITY (4096) |
| 16 | |
| 17 | FILE *write_to_pipe(std::string content) |
| 18 | { |
| 19 | int pipefd[2]; |
| 20 | if (pipe(pipefd) == -1) { |
| 21 | die("pipe(pipefd) failed"); |
| 22 | } |
| 23 | |
| 24 | size_t len = content.length(); |
| 25 | if (len > MAX_PIPE_CAPACITY) |
| 26 | die("write_to_pipe cannot handle >4KB content."); |
| 27 | size_t i = 0; |
| 28 | unsigned int attempts = 0; |
| 29 | ssize_t ret; |
| 30 | while (i < len) { |
| 31 | ret = write(pipefd[1], content.c_str() + i, len - i); |
| 32 | if (ret == -1) { |
| 33 | close(pipefd[0]); |
| 34 | close(pipefd[1]); |
| 35 | return NULL; |
| 36 | } |
| 37 | |
| 38 | /* If we write 0 bytes three times in a row, fail. */ |
| 39 | if (ret == 0) { |
| 40 | if (++attempts >= 3) { |
| 41 | close(pipefd[0]); |
| 42 | close(pipefd[1]); |
| 43 | warn("write() returned 0 three times in a row"); |
| 44 | return NULL; |
| 45 | } |
| 46 | continue; |
| 47 | } |
| 48 | |
| 49 | attempts = 0; |
| 50 | i += (size_t)ret; |
| 51 | } |
| 52 | |
| 53 | close(pipefd[1]); |
| 54 | return fdopen(pipefd[0], "r"); |
| 55 | } |