#include <stdio.h>
#include <unistd.h>
#include <spawn.h>
#include <fcntl.h>
#include <sys/wait.h>
extern char **environ;
int main() {
posix_spawn_file_actions_t actions;
posix_spawnattr_t attr;
int success, status;
pid_t pid;
char *argv[] = {"echo", "hello", "world", NULL};
posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "hello.txt",
O_WRONLY | O_CREAT | O_TRUNC, 0644);
posix_spawnattr_init(&attr);
success = posix_spawn(&pid, "/bin/echo", &actions, &attr, argv, environ);
if (success != 0) {
perror("posix_spawn failed");
return 1;
}
posix_spawn_file_actions_destroy(&actions);
posix_spawnattr_destroy(&attr);
printf("Created child process ID: %d\n", pid);
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("Child exited with status: %d\n", WEXITSTATUS(status));
} else {
printf("Child exited abnormally\n");
}
return 0;
}