3 * This file is part of dds2tar.
4 * Copyright by J"org Weule
10 * If you compile this file with -DTEST, you will get a test program:
12 * cc dds_fio.c -DTEST -o dds_fio && dds_fio
14 * The test shows the use of ccopen(...) to pipe stdout through /bin/grep.
16 * The interface should be useful in many cases.
23 #include <unistd.h> /* pipe() ... */
24 #include <sys/types.h> /* size_t, open() */
25 #include <sys/wait.h> /* wait() */
26 #include <sys/stat.h> /* open() */
27 #include <fcntl.h> /* open() */
29 #include "zf-cre-open.h"
31 #define streq(a,b) (!strcmp((a),(b)))
35 char const *const name,
37 char const *const open_mode
48 if (compressed == T_MODE) {
49 if ((name != NULL) && (strcmp(name, "-"))) {
50 fp = fopen(name, open_mode);
55 } else if (streq(open_mode, "w")) {
62 if (streq(open_mode, "w")) {
64 if ((name != NULL) && (strcmp(name, "-"))) {
68 } else if (streq(open_mode, "r")) {
69 strcpy(b, "gunzip --force --decompress --stdout ");
70 if ((name != NULL) && (strcmp(name, "-"))) {
74 fp = popen(b, open_mode);
97 char const *const output_file,
104 if (!strcmp(output_file, "-")) {
109 if ((fd = open(output_file, mode, flags)) == -1) {
113 /* don't know why this happens. Any idea? */
114 if (fd == 0) { /* normally 0 is stdin!! */
128 * creopen opens a pipe to a child process with the file number 'stdfd'
129 * on file number 'stdfd_child' of the child.
130 * The files are close as needed (see dup2(2)).
135 int const stdfd_parent, /* stdfd should not be == 3 */
136 int const stdfd_child, /* stdfd_child must be 1 or 2 */
137 char const *const filename,
138 char const *const *argv
146 if ((stdfd_child & 0xfffffffe) != 0 || stdfd_child == stdfd_parent) {
147 fprintf(stderr, "creopen not useful with that parameters\n");
150 pipe_parent = stdfd_child ^ 1;
151 if (pipe(pipefd) < 0) { /* create pipe with two fd's */
155 if ((pid = fork()) == 0) { /* we are the child process */
156 /* reconnect pipe to child */
157 dup2(pipefd[stdfd_child], stdfd_child);
158 close(pipefd[0]); /* close input of pipe */
159 close(pipefd[1]); /* close output of pipe */
160 /* the prototype of execv is wrong */
161 execv(filename, (char *const *) argv);
170 * We are the parent process.
173 fd = pipefd[pipe_parent];
174 if ((0 <= stdfd_parent) && (stdfd_parent <= 1)) {
175 dup2(fd, stdfd_parent);
187 {"grep", "allo", NULL};
189 main(int argc, char **argv, char **envp)
196 if (!strcmp(argv[1], "-p")) {
198 if (!strcmp(argv[1], "-o"))
199 reopen(1, argv[2], O_RDONLY, 0);
201 creopen(1, 0, "/usr/bin/grep", a);
202 write(1, "Hallo World -1- \n", 17);
203 write(1, "Hi World -2- \n", 17);
204 write(1, "Hallo World -3- \n", 17);
205 write(1, "Morgen Welt -4- \n", 17);
206 write(1, "Hallo World -5- \n", 17);
207 printf("Hallo World =1= \n");
208 printf("Hi World =2= \n");
209 printf("Hallo World =3= \n");
210 printf("Morgen Welt =4= \n");
211 printf("Hallo World =5= \n");
213 if (!strcmp(argv[1], "-o")) {