plan9port

fork of plan9port with libvec, libstr and libsdb
Log | Files | Refs | README | LICENSE

rdaemon.c (1382B)


      1 #include <stdlib.h>
      2 #include <stdio.h>
      3 #include <unistd.h>
      4 #include <sys/wait.h>
      5 #include <pthread.h>
      6 
      7 #undef waitpid
      8 #undef pipe
      9 #undef wait
     10 
     11 static int sigpid;
     12 static void
     13 sigenable(int sig, int enabled)
     14 {
     15 	sigset_t mask;
     16 	sigemptyset(&mask);
     17 	sigaddset(&mask, sig);
     18 	sigprocmask(enabled ? SIG_UNBLOCK : SIG_BLOCK, &mask, 0);
     19 }
     20 
     21 static void
     22 child(void)
     23 {
     24 	int status, pid;
     25 printf("wait %d in %d\n", sigpid, getpid());
     26 	pid = waitpid(sigpid, &status, __WALL);
     27 	if(pid < 0)
     28 		perror("wait");
     29 	else if(WIFEXITED(status))
     30 		 _exit(WEXITSTATUS(status));
     31 printf("pid %d if %d %d\n", pid, WIFEXITED(status), WEXITSTATUS(status));
     32 	_exit(97);
     33 }
     34 
     35 static void
     36 sigpass(int sig)
     37 {
     38 	if(sig == SIGCHLD){
     39 print("sig\n");
     40 		child();
     41 	}else
     42 		kill(sigpid, sig);
     43 }
     44 
     45 void
     46 _threadsetupdaemonize(void)
     47 {
     48 	int i, n, pid;
     49 	int p[2];
     50 	char buf[20];
     51 
     52 	sigpid = 1;
     53 
     54 	if(pipe(p) < 0)
     55 		abort();
     56 
     57 	signal(SIGCHLD, sigpass);
     58 	switch(pid = fork()){
     59 	case -1:
     60 		abort();
     61 	default:
     62 		close(p[1]);
     63 		break;
     64 	case 0:
     65 		close(p[0]);
     66 		return;
     67 	}
     68 
     69 	sigpid = pid;
     70 
     71 	read(p[0], buf, sizeof buf-1);
     72 print("pipe\n");
     73 	child();
     74 }
     75 
     76 void*
     77 sleeper(void *v)
     78 {
     79 	pthread_mutex_t m;
     80 	pthread_cond_t c;
     81 
     82 	pthread_mutex_init(&m, 0);
     83 	pthread_cond_init(&c, 0);
     84 	pthread_cond_wait(&c, &m);
     85 	return 0;
     86 }
     87 
     88 void
     89 main(int argc, char **argv)
     90 {
     91 	pthread_t pid;
     92 
     93 	_threadsetupdaemonize();
     94 	pthread_create(&pid, 0, sleeper, 0);
     95 	exit(1);
     96 }