pkg-monitoring-plugins/config_test/child_test.c

78 lines
2.7 KiB
C
Raw Normal View History

2013-11-26 22:53:44 +00:00
/* Base code taken from http://www-h.eng.cam.ac.uk/help/tpl/unix/fork.html
* Fix for redhat suggested by Ptere Pramberger, peter@pramberger.at */
2013-11-26 22:53:19 +00:00
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
void popen_sigchld_handler (int);
int childtermd;
int main(){
char str[1024];
int pipefd[2];
pid_t pid;
int status, died;
if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
printf ("Cannot catch SIGCHLD\n");
_exit(-1);
}
pipe (pipefd);
switch(pid=fork()){
case -1:
printf("can't fork\n");
_exit(-1);
2013-11-26 22:53:44 +00:00
case 0 : /* this is the code the child runs */
close(1); /* close stdout */
/* pipefd[1] is for writing to the pipe. We want the output
* that used to go to the standard output (file descriptor 1)
* to be written to the pipe. The following command does this,
2023-10-18 07:29:37 +00:00
* creating a new file descriptor 1 (the lowest available)
2013-11-26 22:53:44 +00:00
* that writes where pipefd[1] goes. */
dup (pipefd[1]); /* points pipefd at file descriptor */
/* the child isn't going to read from the pipe, so
* pipefd[0] can be closed */
2013-11-26 22:53:19 +00:00
close (pipefd[0]);
2013-11-26 22:53:44 +00:00
/* These are the commands to run, with success commented. dig and nslookup only problems */
/*execl ("/bin/date","date",0);*/ /* 100% */
/*execl ("/bin/cat", "cat", "/etc/hosts", 0);*/ /* 100% */
/*execl ("/usr/bin/dig", "dig", "redhat.com", 0);*/ /* 69% */
/*execl("/bin/sleep", "sleep", "1", 0);*/ /* 100% */
execl ("/usr/bin/nslookup","nslookup","redhat.com",0); /* 90% (after 100 tests), 40% (after 10 tests) */
/*execl ("/bin/ping","ping","-c","1","localhost",0);*/ /* 100% */
/*execl ("/bin/ping","ping","-c","1","192.168.10.32",0);*/ /* 100% */
2013-11-26 22:53:19 +00:00
_exit(0);
2013-11-26 22:53:44 +00:00
default: /* this is the code the parent runs */
2013-11-26 22:53:19 +00:00
2013-11-26 22:53:44 +00:00
close(0); /* close stdin */
/* Set file descriptor 0 (stdin) to read from the pipe */
2013-11-26 22:53:19 +00:00
dup (pipefd[0]);
2013-11-26 22:53:44 +00:00
/* the parent isn't going to write to the pipe */
2013-11-26 22:53:19 +00:00
close (pipefd[1]);
2013-11-26 22:53:44 +00:00
/* Now read from the pipe */
2013-11-26 22:53:19 +00:00
fgets(str, 1023, stdin);
2013-11-26 22:53:44 +00:00
/*printf("1st line output is %s\n", str);*/
2013-11-26 22:53:19 +00:00
2013-11-26 22:53:44 +00:00
/*while (!childtermd);*/ /* Uncomment this line to fix */
2013-11-26 22:53:19 +00:00
died= wait(&status);
2013-11-26 22:53:44 +00:00
/*printf("died=%d status=%d\n", died, status);*/
2013-11-26 22:53:19 +00:00
if (died > 0) _exit(0);
else _exit(1);
}
}
void
popen_sigchld_handler (int signo)
{
if (signo == SIGCHLD) {
2013-11-26 22:53:44 +00:00
/*printf("Caught sigchld\n");*/
2013-11-26 22:53:19 +00:00
childtermd = 1;
}
}