]> git.ozlabs.org Git - ccan/blob - ccan/pipecmd/_info
pipecmd: add stderr fd arg.
[ccan] / ccan / pipecmd / _info
1 #include "config.h"
2 #include <stdio.h>
3 #include <string.h>
4
5 /**
6  * pipecmd - code to fork and run a command in a pipe.
7  *
8  * This code is a classic example of how to run a command in a child, while
9  * handling the case where the exec fails.
10  *
11  * License: CC0 (Public domain)
12  * Author: Rusty Russell <rusty@rustcorp.com.au>
13  *
14  * Example:
15  * // Outputs HELLO WORLD
16  * #include <ccan/pipecmd/pipecmd.h>
17  * #include <ccan/err/err.h>
18  * #include <sys/types.h>
19  * #include <sys/wait.h>
20  * #include <unistd.h>
21  * #include <ctype.h>
22  *
23  * // Runs ourselves with an argument, upcases output.
24  * int main(int argc, char **argv)
25  * {
26  *      pid_t child;
27  *      int outputfd, i, status;
28  *      char input[12];
29  *
30  *      if (argc == 2) {
31  *              write(STDOUT_FILENO, "hello world\n", 12);
32  *              exit(0);
33  *      }
34  *      child = pipecmd(&outputfd, NULL, NULL, argv[0], "ignoredarg", NULL);
35  *      if (child < 0)
36  *              err(1, "Creating child");
37  *      if (read(outputfd, input, sizeof(input)) != sizeof(input))
38  *              err(1, "Reading input");
39  *      if (waitpid(child, &status, 0) != child)
40  *              err(1, "Waiting for child");
41  *      for (i = 0; i < sizeof(input); i++)
42  *              printf("%c", toupper(input[i]));
43  *      exit(0);
44  * }
45  */
46 int main(int argc, char *argv[])
47 {
48         /* Expect exactly one argument */
49         if (argc != 2)
50                 return 1;
51
52         if (strcmp(argv[1], "depends") == 0) {
53                 printf("ccan/noerr\n");
54                 return 0;
55         }
56
57         return 1;
58 }