13 FILE *mypopen(const char *command, pid_t *pidptr)
17 if(pipe(pipefd) == -1) return NULL;
21 close(pipefd[PIPE_READ]);
22 close(pipefd[PIPE_WRITE]);
28 close(pipefd[PIPE_WRITE]);
29 FILE *fp = fdopen(pipefd[PIPE_READ], "r");
36 for(i = sysconf(_SC_OPEN_MAX); i > 0; i--)
37 if(i != STDIN_FILENO && i != STDERR_FILENO && i != pipefd[PIPE_WRITE]) close(i);
39 // move the pipe to stdout
40 if(pipefd[PIPE_WRITE] != STDOUT_FILENO) {
41 dup2(pipefd[PIPE_WRITE], STDOUT_FILENO);
42 close(pipefd[PIPE_WRITE]);
45 #ifdef DETACH_PLUGINS_FROM_NETDATA
46 // this was an attempt to detach the child and use the suspend mode charts.d
47 // unfortunatelly it does not work as expected.
49 // fork again to become session leader
51 if(pid == -1) fprintf(stderr, "Cannot fork again on pid %d\n", getpid());
57 // set a new process group id for just this child
58 if( setpgid(0, 0) != 0 )
59 fprintf(stderr, "Cannot set a new process group for pid %d (%s)\n", getpid(), strerror(errno));
61 if( getpgid(0) != getpid() )
62 fprintf(stderr, "Process group set is incorrect. Expected %d, found %d\n", getpid(), getpgid(0));
65 fprintf(stderr, "Cannot set session id for pid %d (%s)\n", getpid(), strerror(errno));
67 fprintf(stdout, "MYPID %d\n", getpid());
72 for (i = 1 ; i < 65 ;i++) if(i != SIGSEGV) signal(i, SIG_DFL);
74 fprintf(stderr, "executing command: '%s' on pid %d.\n", command, getpid());
75 execl("/bin/sh", "sh", "-c", command, NULL);
79 void mypclose(FILE *fp)
81 // this is a very poor implementation of pclose()
82 // the caller should catch SIGCHLD and waitpid() on the exited child
83 // otherwise the child will be a zombie forever
88 void process_childs(int wait)
91 int options = WEXITED;
92 if(!wait) options |= WNOHANG;
95 while(waitid(P_ALL, 0, &info, options) == 0) {
96 if(!info.si_pid) break;
97 switch(info.si_code) {
99 error("pid %d exited with code %d.", info.si_pid, info.si_status);
103 error("pid %d killed by signal %d.", info.si_pid, info.si_status);
107 error("pid %d core dumped by signal %d.", info.si_pid, info.si_status);
111 error("pid %d stopped by signal %d.", info.si_pid, info.si_status);
115 error("pid %d trapped by signal %d.", info.si_pid, info.si_status);
119 error("pid %d continued by signal %d.", info.si_pid, info.si_status);
123 error("pid %d gave us a SIGCHLD with code %d and status %d.", info.si_pid, info.si_code, info.si_status);
127 // prevent an infinite loop