Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Remove debugging fprintf
[simgrid.git] / tools / tesh / run_context.c
1 /* run_context -- stuff in which TESH runs a command                        */
2
3 /* Copyright (c) 2007, 2008, 2009, 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include "tesh.h"
10
11 #include <signal.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <sys/stat.h>
15 #include <unistd.h>
16
17 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(tesh);
18
19 int fg_job = 0;
20 xbt_dynar_t bg_jobs = NULL;
21 rctx_t armageddon_initiator = NULL;
22 xbt_os_mutex_t armageddon_mutex = NULL;
23 struct {
24   int num;
25   struct sigaction act;
26 } oldact[3];                    /* SIGINT, SIGQUIT, SIGTERM */
27
28 xbt_os_thread_t sigwaiter_thread;
29 xbt_os_mutex_t sigwaiter_mutex;
30 xbt_os_cond_t sigwaiter_cond;
31 int armageddon_requested = 0;
32 int caught_signum = 0;
33
34 /*
35  * Module management
36  */
37
38 static void armageddon_sighandler(int signum)
39 {
40   xbt_os_mutex_acquire(sigwaiter_mutex);
41   caught_signum = signum;
42   armageddon_requested = 1;
43   xbt_os_cond_signal(sigwaiter_cond);
44   xbt_os_mutex_release(sigwaiter_mutex);
45 }
46
47 static void *armageddon_sigwaiter(_XBT_GNUC_UNUSED void *arg)
48 {
49   xbt_os_mutex_acquire(sigwaiter_mutex);
50   /* Inform main thread that it started. */
51   xbt_os_cond_signal(sigwaiter_cond);
52   /* Wait for ending signal... */
53   xbt_os_cond_wait(sigwaiter_cond, sigwaiter_mutex);
54   if (armageddon_requested) {
55     ERROR2("Test suite `%s': caught signal %d", testsuite_name, caught_signum);
56     rctx_armageddon(rctx, 3);
57   }
58   xbt_os_mutex_release(sigwaiter_mutex);
59   return NULL;
60 }
61
62 static void wait_it(rctx_t rctx)
63 {
64   VERB2("Join thread %p which were running background cmd <%s>",
65         rctx->runner, rctx->filepos);
66   xbt_os_thread_join(rctx->runner, NULL);
67 }
68
69 static void kill_it(void *r)
70 {
71   rctx_t rctx = *(rctx_t *) r;
72   wait_it(rctx);
73   rctx_free(rctx);
74 }
75
76 void rctx_init(void)
77 {
78   struct sigaction newact;
79   int i;
80   fg_job = 0;
81   bg_jobs = xbt_dynar_new_sync(sizeof(rctx_t), kill_it);
82   armageddon_mutex = xbt_os_mutex_init();
83   armageddon_initiator = NULL;
84   sigwaiter_mutex = xbt_os_mutex_init();
85   sigwaiter_cond = xbt_os_cond_init();
86   xbt_os_mutex_acquire(sigwaiter_mutex);
87   sigwaiter_thread = xbt_os_thread_create("Armaggedon request waiter",
88                                           armageddon_sigwaiter, NULL, NULL);
89   /* Wait for thread to start... */
90   xbt_os_cond_wait(sigwaiter_cond, sigwaiter_mutex);
91   xbt_os_mutex_release(sigwaiter_mutex);
92   memset(&newact, 0, sizeof(newact));
93   newact.sa_handler = armageddon_sighandler;
94   oldact[0].num = SIGINT;
95   oldact[1].num = SIGQUIT;
96   oldact[2].num = SIGTERM;
97   for (i = 0; i < 3; i++)
98     sigaction(oldact[i].num, &newact, &oldact[i].act);
99 }
100
101 void rctx_exit(void)
102 {
103   int i;
104   for (i = 0; i < 3; i++)
105     sigaction(oldact[i].num, &oldact[i].act, NULL);
106   xbt_os_cond_signal(sigwaiter_cond);
107   xbt_os_thread_join(sigwaiter_thread, NULL);
108   xbt_dynar_free(&bg_jobs);
109   xbt_os_cond_destroy(sigwaiter_cond);
110   xbt_os_mutex_destroy(sigwaiter_mutex);
111   xbt_os_mutex_destroy(armageddon_mutex);
112 }
113
114 void rctx_wait_bg(void)
115 {
116   /* Do not use xbt_dynar_free or it will lock the dynar, preventing armageddon
117    * from working */
118   while (xbt_dynar_length(bg_jobs)) {
119     rctx_t rctx = xbt_dynar_getlast_as(bg_jobs, rctx_t);
120     wait_it(rctx);
121     xbt_dynar_pop(bg_jobs, &rctx);
122     rctx_free(rctx);
123   }
124   xbt_dynar_reset(bg_jobs);
125 }
126
127 static void rctx_armageddon_kill_one(rctx_t initiator, const char *filepos,
128                                      rctx_t rctx)
129 {
130   if (rctx != initiator) {
131     INFO2("Kill <%s> because <%s> failed", rctx->filepos, filepos);
132     xbt_os_mutex_acquire(rctx->interruption);
133     if (!rctx->reader_done) {
134       rctx->interrupted = 1;
135       kill(rctx->pid, SIGTERM);
136       usleep(100);
137       kill(rctx->pid, SIGKILL);
138     }
139     xbt_os_mutex_release(rctx->interruption);
140   }
141 }
142
143 void rctx_armageddon(rctx_t initiator, int exitcode)
144 {
145   unsigned int cursor;
146   rctx_t job;
147   const char *filepos = initiator && initiator->filepos ?
148       initiator->filepos : "(master)";
149
150   DEBUG2("Armageddon request by <%s> (exit=%d)", filepos, exitcode);
151   xbt_os_mutex_acquire(armageddon_mutex);
152   if (armageddon_initiator != NULL) {
153     VERB0("Armageddon already started. Let it go");
154     xbt_os_mutex_release(armageddon_mutex);
155     return;
156   }
157   DEBUG1("Armageddon request by <%s> got the lock. Let's go amok",
158          filepos);
159   armageddon_initiator = initiator;
160   xbt_os_mutex_release(armageddon_mutex);
161
162   /* Kill foreground command */
163   if (fg_job)
164     rctx_armageddon_kill_one(initiator, filepos, rctx);
165
166   /* Kill any background commands */
167   xbt_dynar_foreach(bg_jobs, cursor, job) {
168     rctx_armageddon_kill_one(initiator, filepos, job);
169   }
170
171   /* Give runner threads a chance to acknowledge the processes deaths */
172   usleep(10000);
173   /* Ensure that nobody is running rctx_wait on exit */
174   if (fg_job)
175     xbt_os_mutex_acquire(rctx->interruption);
176   xbt_dynar_foreach(bg_jobs, cursor, job)
177     xbt_os_mutex_acquire(job->interruption);
178   VERB0("Shut everything down!");
179   exit(exitcode);
180 }
181
182 /*
183  * Memory management
184  */
185
186 void rctx_empty(rctx_t rc)
187 {
188   int i;
189   char **env_it;
190   void *filepos;
191
192   if (rc->cmd)
193     free(rc->cmd);
194   rc->cmd = NULL;
195   /* avoid race with rctx_armageddon log messages */
196   filepos = rc->filepos;
197   rc->filepos = NULL;
198   if (filepos)
199     free(filepos);
200   for (i = 0, env_it = environ; *env_it; i++, env_it++);
201   if (rc->env) {
202     for (env_it = rctx->env + i; *env_it; env_it++)
203       free(*env_it);
204     free(rc->env);
205   }
206   rc->env_size = i + 1;
207   rc->env = malloc(rc->env_size * sizeof(char *));
208   memcpy(rc->env, environ, rc->env_size * sizeof(char *));
209
210   rc->is_empty = 1;
211   rc->is_background = 0;
212   rc->is_stoppable = 0;
213   rc->output = e_output_check;
214   rc->output_sort = 0;
215   rc->brokenpipe = 0;
216   rc->timeout = 0;
217   rc->interrupted = 0;
218   xbt_strbuff_empty(rc->input);
219   xbt_strbuff_empty(rc->output_wanted);
220   xbt_strbuff_empty(rc->output_got);
221 }
222
223
224 rctx_t rctx_new()
225 {
226   rctx_t res = xbt_new0(s_rctx_t, 1);
227
228   res->input = xbt_strbuff_new();
229   res->output_sort = 0;
230   res->output_wanted = xbt_strbuff_new();
231   res->output_got = xbt_strbuff_new();
232   res->interruption = xbt_os_mutex_init();
233   rctx_empty(res);
234   return res;
235 }
236
237 void rctx_free(rctx_t rctx)
238 {
239   DEBUG1("RCTX: Free %p", rctx);
240   rctx_dump(rctx, "free");
241   if (!rctx)
242     return;
243
244   if (rctx->cmd)
245     free(rctx->cmd);
246   if (rctx->filepos)
247     free(rctx->filepos);
248   if (rctx->env) {
249     int i;
250     char **env_it;
251     for (i = 0, env_it = environ; *env_it; i++, env_it++);
252     for (env_it = rctx->env + i; *env_it; env_it++)
253       free(*env_it);
254     free(rctx->env);
255   }
256   xbt_os_mutex_destroy(rctx->interruption);
257   xbt_strbuff_free(rctx->input);
258   xbt_strbuff_free(rctx->output_got);
259   xbt_strbuff_free(rctx->output_wanted);
260   free(rctx);
261 }
262
263 void rctx_dump(rctx_t rctx, const char *str)
264 {
265   DEBUG9("%s RCTX %p={in%p={%d,%10s}, want={%d,%10s}, out={%d,%10s}}",
266          str, rctx,
267          rctx->input, rctx->input->used, rctx->input->data,
268          rctx->output_wanted->used, rctx->output_wanted->data,
269          rctx->output_got->used, rctx->output_got->data);
270   DEBUG5("%s RCTX %p=[cmd%p=%10s, pid=%d]",
271          str, rctx, rctx->cmd, rctx->cmd, rctx->pid);
272
273 }
274
275 /*
276  * Getting instructions from the file
277  */
278
279 void rctx_pushline(const char *filepos, char kind, char *line)
280 {
281
282   switch (kind) {
283   case '$':
284   case '&':
285     if (rctx->cmd) {
286       if (!rctx->is_empty) {
287         ERROR2
288             ("[%s] More than one command in this chunk of lines (previous: %s).\n"
289              " Cannot guess which input/output belongs to which command.",
290              filepos, rctx->cmd);
291         ERROR1("Test suite `%s': NOK (syntax error)", testsuite_name);
292         rctx_armageddon(rctx, 1);
293         return;
294       }
295       rctx_start();
296       VERB1("[%s] More than one command in this chunk of lines", filepos);
297     }
298     if (kind == '&')
299       rctx->is_background = 1;
300     else
301       rctx->is_background = 0;
302
303     rctx->cmd = xbt_strdup(line);
304     rctx->filepos = xbt_strdup(filepos);
305     INFO3("[%s] %s%s", filepos, rctx->cmd,
306           ((rctx->is_background) ? " (background command)" : ""));
307
308     break;
309
310   case '<':
311     rctx->is_empty = 0;
312     xbt_strbuff_append(rctx->input, line);
313     xbt_strbuff_append(rctx->input, "\n");
314     break;
315
316   case '>':
317     rctx->is_empty = 0;
318     xbt_strbuff_append(rctx->output_wanted, line);
319     xbt_strbuff_append(rctx->output_wanted, "\n");
320     break;
321
322   case '!':
323     if (rctx->cmd)
324       rctx_start();
325
326     if (!strncmp(line, "timeout no", strlen("timeout no"))) {
327       VERB1("[%s] (disable timeout)", filepos);
328       timeout_value = -1;
329     } else if (!strncmp(line, "timeout ", strlen("timeout "))) {
330       timeout_value = atoi(line + strlen("timeout"));
331       VERB2("[%s] (new timeout value: %d)", filepos, timeout_value);
332
333     } else if (!strncmp(line, "expect signal ", strlen("expect signal "))) {
334       rctx->expected_signal = strdup(line + strlen("expect signal "));
335       xbt_str_trim(rctx->expected_signal, " \n");
336       VERB2("[%s] (next command must raise signal %s)",
337             filepos, rctx->expected_signal);
338
339     } else if (!strncmp(line, "expect return ", strlen("expect return "))) {
340       rctx->expected_return = atoi(line + strlen("expect return "));
341       VERB2("[%s] (next command must return code %d)",
342             filepos, rctx->expected_return);
343
344     } else if (!strncmp(line, "output sort", strlen("output sort"))) {
345       sort_len = atoi(line + strlen("output sort"));
346       if (sort_len==0)
347         sort_len=SORT_LEN_DEFAULT;
348       rctx->output_sort = 1;
349       VERB1("[%s] (sort output of next command)", filepos);
350
351     } else if (!strncmp(line, "output ignore", strlen("output ignore"))) {
352       rctx->output = e_output_ignore;
353       VERB1("[%s] (ignore output of next command)", filepos);
354
355     } else if (!strncmp(line, "output display", strlen("output display"))) {
356       rctx->output = e_output_display;
357       VERB1("[%s] (ignore output of next command)", filepos);
358
359     } else if (!strncmp(line, "setenv ", strlen("setenv "))) {
360       int len = strlen("setenv ");
361       char *eq = strchr(line + len, '=');
362       char *key = bprintf("%.*s", (int) (eq - line - len), line + len);
363       xbt_dict_set(env, key, xbt_strdup(eq + 1), xbt_free_f);
364       free(key);
365
366       rctx->env = realloc(rctx->env, ++(rctx->env_size) * sizeof(char *));
367       rctx->env[rctx->env_size - 2] = xbt_strdup(line + len);
368       rctx->env[rctx->env_size - 1] = NULL;
369       VERB2("[%s] setenv %s", filepos, line + len);
370
371     } else {
372       ERROR2("%s: Malformed metacommand: %s", filepos, line);
373       ERROR1("Test suite `%s': NOK (syntax error)", testsuite_name);
374       rctx_armageddon(rctx, 1);
375       return;
376     }
377     break;
378   }
379 }
380
381 /*
382  * Actually doing the job
383  */
384
385 /* The IO of the childs are handled by the two following threads
386    (one pair per child) */
387
388 static void *thread_writer(void *r)
389 {
390   int posw;
391   rctx_t rctx = (rctx_t) r;
392   for (posw = 0; posw < rctx->input->used && !rctx->brokenpipe;) {
393     int got;
394     DEBUG1("Still %d chars to write", rctx->input->used - posw);
395     got =
396         write(rctx->child_to, rctx->input->data + posw,
397               rctx->input->used - posw);
398     if (got > 0)
399       posw += got;
400     if (got < 0) {
401       if (errno == EPIPE) {
402         rctx->brokenpipe = 1;
403       } else if (errno != EINTR && errno != EAGAIN && errno != EPIPE) {
404         perror("Error while writing input to child");
405         ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
406         rctx_armageddon(rctx, 4);
407         return NULL;
408       }
409     }
410     DEBUG1("written %d chars so far", posw);
411
412     if (got <= 0)
413       usleep(100);
414   }
415   rctx->input->data[0] = '\0';
416   rctx->input->used = 0;
417   close(rctx->child_to);
418
419   return NULL;
420 }
421
422 static void *thread_reader(void *r)
423 {
424   rctx_t rctx = (rctx_t) r;
425   char *buffout = malloc(4096);
426   int posr, got_pid;
427
428   do {
429     posr = read(rctx->child_from, buffout, 4095);
430     if (posr < 0 && errno != EINTR && errno != EAGAIN) {
431       perror("Error while reading output of child");
432       ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
433       rctx_armageddon(rctx, 4);
434       return NULL;
435     }
436     if (posr > 0) {
437       buffout[posr] = '\0';
438       xbt_strbuff_append(rctx->output_got, buffout);
439     } else {
440       usleep(100);
441     }
442   } while (!rctx->timeout && posr != 0);
443   free(buffout);
444
445   /* let this thread wait for the child so that the main thread can detect the timeout without blocking on the wait */
446   got_pid = waitpid(rctx->pid, &rctx->status, 0);
447   if (got_pid != rctx->pid) {
448     perror(bprintf
449            ("(%s) Cannot wait for the child %s (got pid %d where pid %d were expected;status=%d)",
450             xbt_thread_self_name(), rctx->cmd, (int) got_pid,
451             (int) rctx->pid, rctx->status));
452     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
453     rctx_armageddon(rctx, 4);
454     return NULL;
455   }
456
457   rctx->reader_done = 1;
458   return NULL;
459 }
460
461 /* Special command: mkfile is a built-in creating a file with the input data as content */
462 static void rctx_mkfile(void)
463 {
464   char *filename = xbt_strdup(rctx->cmd + strlen("mkfile "));
465   FILE *OUT;
466   int err;
467   xbt_str_trim(filename, NULL);
468   OUT = fopen(filename, "w");
469   if (!OUT) {
470     THROW3(system_error, errno, "%s: Cannot create file %s: %s",
471            rctx->filepos, filename, strerror(errno));
472   }
473   err = (fprintf(OUT, "%s", rctx->input->data) < 0);
474   err = (fclose(OUT) == -1) || err;
475   if (err) {
476     THROW3(system_error, errno, "%s: Cannot write file %s: %s",
477            rctx->filepos, filename, strerror(errno));
478   }
479   free(filename);
480 }
481
482 /* function to be called from the child to start the actual process */
483 static void start_command(rctx_t rctx)
484 {
485   xbt_dynar_t cmd;
486   char *binary_name = NULL;
487   unsigned int it;
488   char *str;
489   char **args;
490   int errcode;
491
492   if (!strncmp(rctx->cmd, "mkfile ", strlen("mkfile "))) {
493     rctx_mkfile();
494     /* Valgrind detects memory leaks here.
495      * To correct those leaks, we must free objects allocated in main() or in
496      * handle_suite(), but we have no more reference to them at this point.
497      * A quick and dirty hack to make valgrind happy it to uncomment the
498      * following line.
499      */
500     /* execlp("true", "true", (const char *)0); */
501     exit(0);                    /* end the working child */
502   }
503
504   cmd = xbt_str_split_quoted(rctx->cmd);
505   xbt_dynar_get_cpy(cmd, 0, &binary_name);
506   args = xbt_new(char *, xbt_dynar_length(cmd) + 1);
507   xbt_dynar_foreach(cmd, it, str) {
508     args[it] = xbt_strdup(str);
509   }
510   args[it] = NULL;
511   xbt_dynar_free_container(&cmd);
512
513   /* To search for the right executable path when not trivial */
514   struct stat stat_buf;
515
516   /* build the command line */
517   if (stat(binary_name, &stat_buf)) {
518     /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
519     int i;
520
521     for (i = 0; environ[i]; i++) {
522       if (!strncmp("PATH=", environ[i], 5)) {
523         xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
524
525         xbt_dynar_foreach(path, it, str) {
526           if (binary_name)
527             free(binary_name);
528           binary_name = bprintf("%s/%s", str, args[0]);
529           if (!stat(binary_name, &stat_buf)) {
530             /* Found. */
531             DEBUG1("Looked in the PATH for the binary. Found %s",
532                    binary_name);
533             xbt_dynar_free(&path);
534             break;
535           }
536         }
537         xbt_dynar_free(&path);
538         if (stat(binary_name, &stat_buf)) {
539           /* not found */
540           printf("TESH_ERROR Command %s not found\n", args[0]);
541           exit(127);
542         }
543         break;
544       }
545     }
546   } else {
547     binary_name = xbt_strdup(args[0]);
548   }
549
550   errcode = execve(binary_name, args, rctx->env);
551   printf("TESH_ERROR %s: Cannot start %s: %s\n", rctx->filepos, rctx->cmd,
552          strerror(errcode));
553   exit(127);
554 }
555
556 /* Start a new child, plug the pipes as expected and fire up the
557    helping threads. Is also waits for the child to end if this is a
558    foreground job, or fire up a thread to wait otherwise. */
559 void rctx_start(void)
560 {
561   int child_in[2];
562   int child_out[2];
563
564   DEBUG1("Cmd before rewriting %s", rctx->cmd);
565   rctx->cmd = xbt_str_varsubst(rctx->cmd, env);
566   VERB2("Start %s %s", rctx->cmd,
567         (rctx->is_background ? "(background job)" : ""));
568   xbt_os_mutex_acquire(armageddon_mutex);
569   if (armageddon_initiator) {
570     VERB0("Armageddon in progress. Do not start job.");
571     xbt_os_mutex_release(armageddon_mutex);
572     return;
573   }
574   if (pipe(child_in) || pipe(child_out)) {
575     perror("Cannot open the pipes");
576     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
577     xbt_os_mutex_release(armageddon_mutex);
578     rctx_armageddon(rctx, 4);
579   }
580
581   rctx->pid = fork();
582   if (rctx->pid < 0) {
583     perror("Cannot fork the command");
584     ERROR1("Test suite `%s': NOK (system error)", testsuite_name);
585     xbt_os_mutex_release(armageddon_mutex);
586     rctx_armageddon(rctx, 4);
587     return;
588   }
589
590   if (rctx->pid) {              /* father */
591     close(child_in[0]);
592     rctx->child_to = child_in[1];
593
594     close(child_out[1]);
595     rctx->child_from = child_out[0];
596
597     if (timeout_value > 0)
598       rctx->end_time = time(NULL) + timeout_value;
599     else
600       rctx->end_time = -1;
601
602     rctx->reader_done = 0;
603     rctx->reader =
604         xbt_os_thread_create("reader", thread_reader, (void *) rctx, NULL);
605     rctx->writer =
606         xbt_os_thread_create("writer", thread_writer, (void *) rctx, NULL);
607
608   } else {                      /* child */
609     close(child_in[1]);
610     dup2(child_in[0], 0);
611     close(child_in[0]);
612
613     close(child_out[0]);
614     dup2(child_out[1], 1);
615     dup2(child_out[1], 2);
616     close(child_out[1]);
617
618     start_command(rctx);
619   }
620
621   rctx->is_stoppable = 1;
622
623   if (!rctx->is_background) {
624     fg_job = 1;
625     xbt_os_mutex_release(armageddon_mutex);
626     rctx_wait(rctx);
627     fg_job = 0;
628   } else {
629     /* Damn. Copy the rctx and launch a thread to handle it */
630     rctx_t old = rctx;
631     xbt_os_thread_t runner;
632
633     rctx = rctx_new();
634     DEBUG2("RCTX: new bg=%p, new fg=%p", old, rctx);
635
636     DEBUG2("Launch a thread to wait for %s %d", old->cmd, old->pid);
637     runner = xbt_os_thread_create(old->cmd, rctx_wait, (void *) old, NULL);
638     old->runner = runner;
639     VERB3("Launched thread %p to wait for %s %d", runner, old->cmd,
640           old->pid);
641     xbt_dynar_push(bg_jobs, &old);
642     xbt_os_mutex_release(armageddon_mutex);
643   }
644 }
645
646 /* Helper function to sort the output */
647 static int cmpstringp(const void *p1, const void *p2) {
648   /* Sort only using the 19 first chars (date+pid)
649    * If the dates are the same, then, sort using pointer address (be stable wrt output of each process)
650    */
651   const char *s1 = *((const char**) p1);
652   const char *s2 = *((const char**) p2);
653
654   DEBUG2("Compare strings '%s' and '%s'", s1, s2);
655
656   int res = strncmp(s1, s2, sort_len);
657   if (res == 0)
658     return p1>p2;
659   return res;
660 }
661
662
663 /* Waits for the child to end (or to timeout), and check its
664    ending conditions. This is launched from rctx_start but either in main
665    thread (for foreground jobs) or in a separate one for background jobs.
666    That explains the prototype, forced by xbt_os_thread_create. */
667
668 void *rctx_wait(void *r)
669 {
670   rctx_t rctx = (rctx_t) r;
671   int errcode = 0;
672   int now = time(NULL);
673
674   rctx_dump(rctx, "wait");
675
676   if (!rctx->is_stoppable)
677     THROW1(unknown_error, 0, "Cmd '%s' not started yet. Cannot wait it",
678            rctx->cmd);
679
680   /* Wait for the child to die or the timeout to happen (or an armageddon to happen) */
681   while (!rctx->reader_done
682          && (rctx->end_time < 0 || rctx->end_time >= now)) {
683     usleep(100);
684     now = time(NULL);
685   }
686
687   xbt_os_mutex_acquire(rctx->interruption);
688   if (!rctx->interrupted && rctx->end_time > 0 && rctx->end_time < now) {
689     INFO1("<%s> timeouted. Kill the process.", rctx->filepos);
690     rctx->timeout = 1;
691     kill(rctx->pid, SIGTERM);
692     usleep(100);
693     kill(rctx->pid, SIGKILL);
694   }
695
696   /* Make sure helper threads die.
697      Cannot block since they wait for the child we just killed
698      if not already dead. */
699   xbt_os_thread_join(rctx->writer, NULL);
700   xbt_os_thread_join(rctx->reader, NULL);
701
702   /*  xbt_os_mutex_release(rctx->interruption);
703      if (rctx->interrupted)
704      return NULL;
705      xbt_os_mutex_acquire(rctx->interruption); */
706
707   xbt_strbuff_chomp(rctx->output_got);
708   xbt_strbuff_chomp(rctx->output_wanted);
709   xbt_strbuff_trim(rctx->output_got);
710   xbt_strbuff_trim(rctx->output_wanted);
711
712   /* Check for broken pipe */
713   if (rctx->brokenpipe)
714     VERB0
715         ("Warning: Child did not consume all its input (I got broken pipe)");
716
717   /* Check for timeouts */
718   if (rctx->timeout) {
719     if (rctx->output_got->data[0])
720       INFO2("<%s> Output on timeout:\n%s",
721             rctx->filepos, rctx->output_got->data);
722     else
723       INFO1("<%s> No output before timeout", rctx->filepos);
724     ERROR3("Test suite `%s': NOK (<%s> timeout after %d sec)",
725            testsuite_name, rctx->filepos, timeout_value);
726     DEBUG2("<%s> Interrupted = %d", rctx->filepos, rctx->interrupted);
727     if (!rctx->interrupted) {
728       xbt_os_mutex_release(rctx->interruption);
729       rctx_armageddon(rctx, 3);
730       return NULL;
731     }
732   }
733
734   DEBUG2("RCTX=%p (pid=%d)", rctx, rctx->pid);
735   DEBUG3("Status(%s|%d)=%d", rctx->cmd, rctx->pid, rctx->status);
736
737   if (!rctx->interrupted) {
738     if (WIFSIGNALED(rctx->status) && !rctx->expected_signal) {
739       ERROR3("Test suite `%s': NOK (<%s> got signal %s)",
740              testsuite_name, rctx->filepos,
741              signal_name(WTERMSIG(rctx->status), NULL));
742       errcode = WTERMSIG(rctx->status) + 4;
743     }
744
745     if (WIFSIGNALED(rctx->status) && rctx->expected_signal &&
746         strcmp(signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
747                rctx->expected_signal)) {
748       ERROR4("Test suite `%s': NOK (%s got signal %s instead of %s)",
749              testsuite_name, rctx->filepos,
750              signal_name(WTERMSIG(rctx->status), rctx->expected_signal),
751              rctx->expected_signal);
752       errcode = WTERMSIG(rctx->status) + 4;
753     }
754
755     if (!WIFSIGNALED(rctx->status) && rctx->expected_signal) {
756       ERROR3("Test suite `%s': NOK (child %s expected signal %s)",
757              testsuite_name, rctx->filepos, rctx->expected_signal);
758       errcode = 5;
759     }
760
761     if (WIFEXITED(rctx->status)
762         && WEXITSTATUS(rctx->status) != rctx->expected_return) {
763       if (rctx->expected_return)
764         ERROR4
765             ("Test suite `%s': NOK (<%s> returned code %d instead of %d)",
766              testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status),
767              rctx->expected_return);
768       else
769         ERROR3("Test suite `%s': NOK (<%s> returned code %d)",
770                testsuite_name, rctx->filepos, WEXITSTATUS(rctx->status));
771       errcode = 40 + WEXITSTATUS(rctx->status);
772
773     }
774     rctx->expected_return = 0;
775
776     if (rctx->expected_signal) {
777       free(rctx->expected_signal);
778       rctx->expected_signal = NULL;
779     }
780   }
781   while (rctx->output_got->used
782          && !strncmp(rctx->output_got->data, "TESH_ERROR ",
783                      strlen("TESH_ERROR "))) {
784     int marklen = strlen("TESH_ERROR ");
785     char *endline = strchr(rctx->output_got->data, '\n');
786
787     CRITICAL2("%.*s", (int) (endline - rctx->output_got->data - marklen),
788               rctx->output_got->data + marklen);
789     memmove(rctx->output_got->data, rctx->output_got->data + marklen,
790             rctx->output_got->used - marklen);
791     rctx->output_got->used -= endline - rctx->output_got->data + 1;
792     rctx->output_got->data[rctx->output_got->used] = '\0';
793     errcode = 1;
794   }
795
796   if (rctx->output_sort) {
797     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
798     xbt_dynar_sort(a,cmpstringp);
799     char *sorted_output = xbt_str_join(a, "\n");
800     strcpy(rctx->output_got->data, sorted_output);
801     xbt_free(sorted_output);
802     xbt_dynar_free(&a);
803     /* If an empty line moved in first position, move it back to the end */
804     if (rctx->output_got->data[0]=='\n') {
805       memmove(rctx->output_got->data,rctx->output_got->data+1,rctx->output_got->used-1);
806       rctx->output_got->data[rctx->output_got->used-1] = '\n';
807     }
808   }
809   if ((errcode && errcode != 1) || rctx->interrupted) {
810     /* checking output, and matching */
811     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
812     char *out = xbt_str_join(a, "\n||");
813     xbt_dynar_free(&a);
814     INFO2("Output of <%s> so far: \n||%s", rctx->filepos, out);
815     free(out);
816   } else if (rctx->output == e_output_check
817              && (rctx->output_got->used != rctx->output_wanted->used
818                  || strcmp(rctx->output_got->data,
819                            rctx->output_wanted->data))) {
820     if (XBT_LOG_ISENABLED(tesh, xbt_log_priority_info)) {
821       char *diff =
822           xbt_str_diff(rctx->output_wanted->data, rctx->output_got->data);
823       ERROR2("Output of <%s> mismatch:\n%s", rctx->filepos, diff);
824       free(diff);
825     }
826     ERROR2("Test suite `%s': NOK (<%s> output mismatch)",
827            testsuite_name, rctx->filepos);
828
829     errcode = 2;
830   } else if (rctx->output == e_output_ignore) {
831     INFO1("(ignoring the output of <%s> as requested)", rctx->filepos);
832   } else if (rctx->output == e_output_display) {
833     xbt_dynar_t a = xbt_str_split(rctx->output_got->data, "\n");
834     char *out = xbt_str_join(a, "\n||");
835     xbt_dynar_free(&a);
836     INFO1("Here is the (ignored) command output: \n||%s", out);
837     free(out);
838   }
839
840   if (!rctx->is_background) {
841     xbt_os_mutex_acquire(armageddon_mutex);
842     /* Don't touch rctx if armageddon is in progress. */
843     if (!armageddon_initiator)
844       rctx_empty(rctx);
845     xbt_os_mutex_release(armageddon_mutex);
846   }
847   if (errcode) {
848     if (!rctx->interrupted) {
849       xbt_os_mutex_release(rctx->interruption);
850       rctx_armageddon(rctx, errcode);
851       return NULL;
852     }
853   }
854
855   xbt_os_mutex_release(rctx->interruption);
856   return NULL;
857 }