Add ifne, contributed by Javier Merino.
[moreutils.git] / ifne.c
blob9af19fa0f905802af64b90b23fc1dd9963864a50
2 /*
4 * Copyright 2008 Javier Merino <cibervicho@gmail.com>
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 * Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <sys/wait.h>
25 #include <sys/types.h>
27 int main(int argc, char **argv) {
28 ssize_t r;
29 int fds[2];
30 int child_status;
31 pid_t child_pid;
32 char buf[BUFSIZ];
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 in fds[1] our stdin */
72 close(fds[0]);
74 do {
75 if (write(fds[1], buf, r*sizeof(char)) == -1) {
76 fprintf(stderr, "Write error to %s\n", argv[1]);
77 exit(EXIT_FAILURE);
79 r = read(0, buf, BUFSIZ*sizeof(char));
80 } while (r > 0);
81 if (r == -1) {
82 perror("read");
83 exit(EXIT_FAILURE);
86 close(fds[1]);
87 if (waitpid(child_pid, &child_status, 0) != child_pid) {
88 perror("waitpid");
89 return EXIT_FAILURE;
91 if (WIFEXITED(child_status)) {
92 return (WEXITSTATUS(child_status));
93 } else if (WIFSIGNALED(child_status)) {
94 raise(WTERMSIG(child_status));
95 return EXIT_FAILURE;
98 return EXIT_FAILURE;