]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - tests/example.h
tests: Check return values of write() and dup2().
[coloredstderr/coloredstderr.git] / tests / example.h
1 /*
2  * Helper functions/macros for example files.
3  *
4  * Copyright (C) 2013  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20
21 #define FORKED_TEST(pid) \
22     pid = fork(); \
23     if (pid == -1) { \
24         perror("fork"); \
25         exit(EXIT_FAILURE); \
26     } else if (pid != 0) { \
27         int status; \
28         if (waitpid(pid, &status, 0) == -1) { \
29             perror("waitpid"); \
30             exit(EXIT_FAILURE); \
31         } \
32         if (WIFEXITED(status)) { \
33             printf("exit code: %d\n", WEXITSTATUS(status)); \
34         } else { \
35             printf("child terminated!\n"); \
36         } \
37         fflush(stdout); \
38     } else
39
40 static ssize_t xwrite(int fd, void const *buf, size_t count) {
41     ssize_t result = write(fd, buf, count);
42     if (result == -1) {
43         perror("write");
44         exit(EXIT_FAILURE);
45     }
46     /* Ignore short writes here. Doesn't matter for test cases. */
47     return result;
48 }
49
50 static int xdup2(int oldfd, int newfd) {
51     int result = dup2(oldfd, newfd);
52     if (result == -1) {
53         perror("dup2");
54         exit(EXIT_FAILURE);
55     }
56     return result;
57 }