Blob


1 #define NOPLAN9DEFINES
2 #include <u.h>
3 #include <libc.h>
5 #include <signal.h>
6 #include <sys/types.h>
7 #include <sys/time.h>
8 #include <sys/resource.h>
9 #include <sys/wait.h>
11 static struct {
12 int sig;
13 char *str;
14 } tab[] = {
15 SIGHUP, "hangup",
16 SIGINT, "interrupt",
17 SIGQUIT, "quit",
18 SIGILL, "sys: illegal instruction",
19 SIGTRAP, "sys: breakpoint",
20 SIGABRT, "sys: abort",
21 #ifdef SIGEMT
22 SIGEMT, "sys: emulate instruction executed",
23 #endif
24 SIGFPE, "sys: fp: trap",
25 SIGKILL, "sys: kill",
26 SIGBUS, "sys: bus error",
27 SIGSEGV, "sys: segmentation violation",
28 SIGALRM, "alarm",
29 SIGTERM, "kill",
30 SIGURG, "sys: urgent condition on socket",
31 SIGSTOP, "sys: stop",
32 SIGTSTP, "sys: tstp",
33 SIGCONT, "sys: cont",
34 SIGCHLD, "sys: child",
35 SIGTTIN, "sys: ttin",
36 SIGTTOU, "sys: ttou",
37 SIGIO, "sys: i/o possible on fd",
38 SIGXCPU, "sys: cpu time limit exceeded",
39 SIGXFSZ, "sys: file size limit exceeded",
40 SIGVTALRM, "sys: virtual time alarm",
41 SIGPROF, "sys: profiling timer alarm",
42 SIGWINCH, "sys: window size change",
43 #ifdef SIGINFO
44 SIGINFO, "sys: status request",
45 #endif
46 SIGUSR1, "sys: usr1",
47 SIGUSR2, "sys: usr2",
48 SIGPIPE, "sys: write on closed pipe",
49 };
51 char*
52 _p9sigstr(int sig, char *tmp)
53 {
54 int i;
56 for(i=0; i<nelem(tab); i++)
57 if(tab[i].sig == sig)
58 return tab[i].str;
59 if(tmp == nil)
60 return nil;
61 sprint(tmp, "sys: signal %d", sig);
62 return tmp;
63 }
65 int
66 _p9strsig(char *s)
67 {
68 int i;
70 for(i=0; i<nelem(tab); i++)
71 if(strcmp(s, tab[i].str) == 0)
72 return tab[i].sig;
73 return 0;
74 }
76 static int
77 _await(int pid4, char *str, int n, int opt)
78 {
79 int pid, status, cd;
80 struct rusage ru;
81 char buf[128], tmp[64];
82 ulong u, s;
84 for(;;){
85 /* On Linux, pid==-1 means anyone; on SunOS, it's pid==0. */
86 if(pid4 == -1)
87 pid = wait3(&status, opt, &ru);
88 else
89 pid = wait4(pid4, &status, opt, &ru);
90 if(pid <= 0)
91 return -1;
92 u = ru.ru_utime.tv_sec*1000+((ru.ru_utime.tv_usec+500)/1000);
93 s = ru.ru_stime.tv_sec*1000+((ru.ru_stime.tv_usec+500)/1000);
94 if(WIFEXITED(status)){
95 status = WEXITSTATUS(status);
96 if(status)
97 snprint(buf, sizeof buf, "%d %lud %lud %lud %d", pid, u, s, u+s, status);
98 else
99 snprint(buf, sizeof buf, "%d %lud %lud %lud ''", pid, u, s, u+s, status);
100 strecpy(str, str+n, buf);
101 return strlen(str);
103 if(WIFSIGNALED(status)){
104 cd = WCOREDUMP(status);
105 snprint(buf, sizeof buf, "%d %lud %lud %lud 'signal: %s%s'", pid, u, s, u+s, _p9sigstr(WTERMSIG(status), tmp), cd ? " (core dumped)" : "");
106 strecpy(str, str+n, buf);
107 return strlen(str);
112 int
113 await(char *str, int n)
115 return _await(-1, str, n, 0);
118 int
119 awaitnohang(char *str, int n)
121 return _await(-1, str, n, WNOHANG);
124 int
125 awaitfor(int pid, char *str, int n)
127 return _await(pid, str, n, 0);