Zoklet.net

Go Back   Zoklet.net > Technology > Technophiles and Technophiliacs > Codes of all kinds

Reply
 
Thread Tools
  #1  
Old 01-21-2009, 02:35 AM
zeusy|Nemsis zeusy|Nemsis is offline
Member
 
Join Date: Jan 2009
Thanks: 0
Thanked 0 Times in 0 Posts
Default Output redirection and daemonization

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);
}
Reply With Quote
Reply

Bookmarks

Tags
daemonization, output, redirection

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 10:44 AM.


Hot Topics
On IRC
Users: 4
Messages/minute: 0
Topic: "http://www.zoklet.net/..."
Users: 22
Messages/minute: 0
Topic: "buttpee"
Users: 10
Messages/minute: 0
Topic: "11:37 < mib_i8mfin> so wie ich die website hier sehe las..."
Advertisements
Your ad could go right HERE! Contact us!

Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.