/* Sample of attaching a file to stdout before execing a command. This expects a file name on the command line, this is the "log file". This program runs the who command after attaching a file to STDOUT with O_APPEND set (so that who will append to the file) File is opened and duped to file descriptor 1 (stdout). When opening the file we need to specify: 1. O_APPEND | O_CREAT - means open for appending and it's OK to create the file if it doesnt' exist. 2. mode set to 0755 owner can do anything group and others can read and execute Then the who command is exec'd. */ #include #include #include #include #include #include int main(int argc, char **argv) { int fd; /* Make sure we got a file name on the command line */ if (argc<2) { printf("Error - you need to specify what file to save output in!\n"); exit(1); } /* attempt to open the file for appending only It's OK to create the file if it doesn't already exist */ fd = open(argv[1],O_WRONLY | O_APPEND | O_CREAT,0755); if (fd<0) { perror("Fatal Error"); exit(1); } /* close STDOUT and assign descriptor 1 to same file as fd refers to */ if (dup2(fd,STDOUT_FILENO)<0) { perror("duping error"); exit(1); } /* everything is set for the exec - now become who (which will write to stdout). */ execlp("who","who",NULL); /* we should never get here! (exec failed) */ perror("Error execing who"); return(0); }