Linux get daemon process console data

  
        Linux provides a daemon function that allows the process to run off the console and achieve background effects. However, after the process runs in the background, the data originally output on the terminal console will not be visible. So how can I retrieve this data? Here, the topic of the article revolves around how to get the console data of the background process, the principle of which should start from the daemon. The daemon mainly does two things: 1. Create a child process, exit the current process, and create a new session as a child process. Thus, even if the parent process exits, the child process will not be closed.

2. Standard input, standard output, and standard error are redirected to /dev/null

The daemon implementation is roughly as follows:
< Pre>int daemonize(int nochdir, int noclose) { int fd; switch (fork()) { case -1: return (-1); case 0: break; default: _exit(EXIT_SUCCESS); } if (setsid() == -1) return (-1); if (nochdir == 0) { if(chdir("/") != 0) { perror("chdir"); return (-1); } } If (noclose == 0 && (fd = open("/dev/null", O_RDWR, 0)) != -1) { if(dup2(fd, STDIN_FILENO) < 0) { perror(" ;dup2 stdin"); return (-1); } if(dup2(fd, STDOUT_FILENO) < 0) { perror("dup2 stdout"); return (-1); } if(dup2(fd, STDERR_FILENO) < 0) { perror("dup2 stderr"); return (-1); } if (fd > STDERR_FILENO) { if(close(fd) < 0) { perror("close"); return ( -1); } } } return (0);} So, if you want to retrieve the console data of the process, just put the standard output Standard error is redirected to the specified file, and then read the file just fine. The article here writes an example, a simple demonstration (here through the kill signal to complete the process communication, a bit rough) code is as follows, saved as daemon_example.c

#include #include #include #include static int fd = -1;void sigroutine (int dunno) { switch (dunno) { case SIGUSR1: fprintf(stderr, "Get a signal -- SIGUSR1 \ "); if (fd != -1) close(fd); fd = open("/Tmp/console_temp.log", O_RDWR
						
Copyright © Windows knowledge All Rights Reserved