Browse Source Download (without any required ccan dependencies)
pipecmd
code to fork and run a command in a pipe.
Rusty Russell <[email protected]>
This code is a classic example of how to run a command in a child, while handling the case where the exec fails.
// Outputs HELLO WORLD
#include <ccan/pipecmd/pipecmd.h>
#include <ccan/err/err.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <ctype.h>
// Runs ourselves with an argument, upcases output.
int main(int argc, char **argv)
{
pid_t child;
int outputfd, i, status;
char input[12];
if (argc == 2) {
if (write(STDOUT_FILENO, "hello world\n", 12) != 12)
exit(1);
exit(0);
}
child = pipecmd(NULL, &outputfd, NULL, argv[0], "ignoredarg", NULL);
if (child < 0)
err(1, "Creating child");
if (read(outputfd, input, sizeof(input)) != sizeof(input))
err(1, "Reading input");
if (waitpid(child, &status, 0) != child)
err(1, "Waiting for child");
for (i = 0; i < sizeof(input); i++)
printf("%c", toupper(input[i]));
exit(0);
}
CC0 (Public domain)