int main(int argc, char *argv[]) { pager = getenv("PAGER"); if (pager == NULL) pager = "less"; /* Set number of processes and pipes depending on if we should run grep */ args = (argc > 1) ? 1 : 0; num_procs = 3 + args; num_pipes = 2 + args; pipes_init(); exec_proc(STDIN_FILENO, pipes[0][1], "printenv", argv); if (args) { exec_proc(pipes[0][0], pipes[args][1], "grep", argv); } exec_proc(pipes[args][0], pipes[1 + args][1], "sort", argv); exec_proc(pipes[1 +args][0], STDOUT_FILENO, "less", argv); close_all_fd(); wait_for_kids(); return 0; }
void wf_daemon_action(int nochdir, int noclose, __sighandler_t exit_call) { int i, fd; pid_t pid; struct rlimit rl; struct sigaction sa; // clear file creation mask umask(0); if(getrlimit(RLIMIT_NOFILE, &rl) < 0) rl.rlim_max = 0; pid = fork(); if(pid < 0) exit(1); else if(pid == 0) exit(0); else setsid(); sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGHUP, &sa, NULL); if(fork()!= 0) exit(0); if(!nochdir) chdir("/"); if(rl.rlim_max == 0) close_all_fd(!noclose); else{ if(rl.rlim_max == RLIM_INFINITY) rl.rlim_max = 1024; for(i = noclose ? 3 : 0; i<rl.rlim_max; i++) close(i); } if(!noclose){ fd = open("/dev/null", O_WRONLY); if(fd >= 0){ if(fd != STDOUT_FILENO) dup2(fd, STDOUT_FILENO); if(fd != STDERR_FILENO) dup2(fd, STDERR_FILENO); close(fd); } } signal(SIGINT, exit_call); signal(SIGTERM, exit_call); }
static void __core_restart(int soft) { char exe[PATH_MAX]; pthread_sigmask(SIG_SETMASK, &orig_set, NULL); #ifdef USE_BACKUP if (soft) backup_restore_fd(); else #endif close_all_fd(); sprintf(exe, "/proc/%u/exe", getpid()); readlink(exe, exe, PATH_MAX); while (1) { execv(exe, argv); sleep(3); } }
/* Forks and executes the "program" with arguments args in a different process. STDIN and STDOUT are redirected to fd_in and fd_out and used for the required inter-process communication. */ pid_t exec_proc(int fd_in, int fd_out, char *program, char *argv[]) { pid_t pid = fork(); if (pid == 0) { /*Duplicate stdin and stdout file descriptors*/ int ret; char *ptr[2]; ret = dup2(fd_in, STDIN_FILENO); if (ret == -1) { perror("exec_proc\n"); exit(-1); } ret = dup2(fd_out, STDOUT_FILENO); if (ret == -1) { perror("exec_proc\n"); exit(-1); } /* Close all file descriptors in pipes */ close_all_fd(); /* NULL args for all programs but grep */ ptr[0] = program; ptr[1] = (char*) NULL; /* Execute */ if (!strcmp(program, "grep")) { execvp(program, argv); exit(-1); } else if (!strcmp(program, pager)) { int exec_ret; exec_ret = execvp(program, ptr); /* If pager fails, default to more */ if (exec_ret == -1) { execvp("more", ptr); } } else { execvp(program, ptr); exit(-1); } } else if (pid == -1) { perror("exec_proc"); exit(-1); } return pid; }