Redirect the output of a command to a file and detaches it from the parent process.
(Can be used to make an application continue running even after logout)
Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
void usage(char *command) {
printf("%s: outputfile command args\n", command);
_exit(0);
}
int main(int argc, char *argv[], char *envp[]) {
pid_t forxed;
int fd, error;
char **args = &argv[2];
if (argc < 3)
usage(argv[0]);
if ((forxed = fork()) == 0) {
/* Replace stderr and stdout
* with our file's fd
*/
fd = open(argv[1], O_APPEND | O_WRONLY);
if (fd < 0)
goto error;
error = dup2(fd, 1) + dup2(fd, 2);
if (error != 3)
goto error;
execvp(argv[2], args);
goto error;
} else {
/* Kill the parent with
* a fork >:). Only way
* to semi-daemonize...
*/
_exit(0);
}
error:
perror("Error");
_exit(1);
}