#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include <spawn.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
int ret;
int pout[2];
if(pipe(pout)) {
perror("pipe");
return 1;
}
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_adddup2(&actions, pout[1], 1);
char *args[10];
args[0] = "/bin/printf";
args[1] = "%s\n%f\n%s\n";
args[2] = "Hello World";
args[3] = "3.14";
args[4] = "posix_spawn test";
args[5] = NULL;
char *env[10];
env[0] = "LC_ALL=C";
env[1] = NULL;
pid_t child;
ret = posix_spawn(
&child,
"/bin/printf",
&actions,
NULL,
args,
env);
posix_spawn_file_actions_destroy(&actions);
if(ret) {
perror("posix_spawn");
return 1;
}
close(pout[1]);
char buf[1024];
ssize_t r;
int linestart = 1;
while((r=read(pout[0], buf, 1024)) > 0) {
for(int i=0;i<r;i++) {
if(linestart) {
printf("stdout: [");
linestart = 0;
}
if(buf[i] == '\n') {
printf("]\n");
linestart = 1;
} else {
putchar(buf[i]);
}
}
}
int status;
waitpid(child, &status, 0);
return 0;
}