update physmem copyright
[moreutils.git] / ifne.c
blob817b1c510c92e581233bc19dc3c920b6c2c17181
1 /*
3 * Copyright 2008 Javier Merino <cibervicho@gmail.com>
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
12 * Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <sys/wait.h>
24 #include <sys/types.h>
26 int main(int argc, char **argv) {
27 ssize_t r;
28 int fds[2];
29 int child_status;
30 pid_t child_pid;
31 char buf[BUFSIZ];
32 FILE *outf;
34 if (argc < 2) {
35 /* Noop */
36 return EXIT_SUCCESS;
39 r = read(0, buf, BUFSIZ*sizeof(char));
41 if (r == 0)
42 return EXIT_SUCCESS;
43 else if (r == -1) {
44 perror("read");
45 return EXIT_FAILURE;
48 if (pipe(fds)) {
49 perror("pipe");
50 return EXIT_FAILURE;
53 child_pid = fork();
54 if (!child_pid) {
55 /* child process: rebind stdin and exec the subcommand */
56 close(fds[1]);
57 if (dup2(fds[0], 0)) {
58 perror("dup2");
59 return EXIT_FAILURE;
62 execvp(argv[1], &argv[1]);
63 perror(argv[1]);
64 close(fds[0]);
65 return EXIT_FAILURE;
66 } else if (child_pid == -1) {
67 perror("fork");
68 return EXIT_FAILURE;
71 /* Parent: write stdin to fds[1] */
72 close(fds[0]);
73 outf = fdopen(fds[1], "w");
74 if (! outf) {
75 perror("fdopen");
76 exit(1);
78 do {
79 if (fwrite(buf, r*sizeof(char), 1, outf) < 1) {
80 fprintf(stderr, "Write error to %s\n", argv[1]);
81 exit(EXIT_FAILURE);
83 r = read(0, buf, BUFSIZ*sizeof(char));
84 } while (r > 0);
85 if (r == -1) {
86 perror("read");
87 exit(EXIT_FAILURE);
89 fclose(outf);
91 if (waitpid(child_pid, &child_status, 0) != child_pid) {
92 perror("waitpid");
93 return EXIT_FAILURE;
95 if (WIFEXITED(child_status)) {
96 return (WEXITSTATUS(child_status));
97 } else if (WIFSIGNALED(child_status)) {
98 raise(WTERMSIG(child_status));
99 return EXIT_FAILURE;
102 return EXIT_FAILURE;