Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <errno.h>
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #define STDOUT 1
- #define STDERR 2
- int main(int argc, char **argv)
- {
- pid_t pid;
- if (argc < 2) {
- fprintf(stderr, "Usage: %s command args ...\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- pid = fork();
- if (pid == 0) { /* child */
- int bout, berr; /* backup stdout and stderr */
- int rval;
- int fd = open("output", O_APPEND | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
- if (fd < 0) {
- fprintf(stderr, "Error: open %s\n", strerror(errno));
- exit(EXIT_FAILURE);
- }
- bout = dup(STDOUT);
- berr = dup(STDERR);
- if (bout == -1 ||
- berr == -1)
- {
- fprintf(stderr, "Error: dup (STDOUT|STDERR) %s\n", strerror(errno));
- exit(EXIT_FAILURE);
- }
- rval = dup2(fd, STDOUT);
- if (rval < 0) {
- fprintf(stderr, "Error: dup2 (STDOUT) %s\n", strerror(errno));
- exit(EXIT_FAILURE);
- }
- rval = dup2(fd, STDERR);
- if (rval < 0) {
- fprintf(stderr, "Error: dup2 (STDERR) %s\n", strerror(errno));
- exit(EXIT_FAILURE);
- }
- argv++;
- rval = execv(argv[0], argv);
- if (rval == -1) {
- char message[256];
- snprintf(message, 256, "Error: execv %s\n", strerror(errno));
- write(berr, message, strlen(message));
- exit(EXIT_FAILURE);
- }
- return 0;
- } else if (pid > 0) { /* parent */
- return waitpid(pid);
- } else { /* fork error */
- fprintf(stderr, "Error: %s\n", strerror(errno));
- exit(EXIT_FAILURE);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement