Skip to content

Instantly share code, notes, and snippets.

@CrBoy
Created December 28, 2011 04:52
Show Gist options
  • Save CrBoy/1526380 to your computer and use it in GitHub Desktop.
Save CrBoy/1526380 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void redirect_to(char *filename)
{
int fd = open(filename, O_RDWR | O_CREAT, 0666);
if(fd == -1){
perror("open");
return;
}
dup2(fd,STDOUT_FILENO);
dup2(fd,STDERR_FILENO);
close(fd);
}
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if(pid < 0){
fprintf(stderr, "Fork failed.\n");
}else if(pid > 0){
redirect_to("log");
execl("/bin/ls", "ls", "-l", (char*)0);
}else{
redirect_to("log2");
printf("abc\n");
fprintf(stderr, "123\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment