#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
extern char **environ;
int main() {
int status;
pid_t pid = fork();
if (pid == 0) { // Child process
char *argv[] = {"echo", "hello", "world", NULL};
int fd = open("hello.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd != -1) {
dup2(fd, STDOUT_FILENO); // Redirect stdout to the file
close(fd);
}
execve("/bin/echo", argv, environ); // Should never return!
_exit(1); // In case exec fails
}
// Parent process
if (pid == -1) {
perror("fork failed");
return 1;
}
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;
}
hello world