summaryrefslogtreecommitdiff
path: root/src/common.c
blob: 558dedf17c40672627fb57cd14cd69aa4af87ebe (plain)
    1 // 
    2 // Copyright (C) 2015 Aaron Ball <nullspoon@iohq.net>
    3 // 
    4 // Cnetbench is free software: you can redistribute it and/or modify
    5 // it under the terms of the GNU General Public License as published by
    6 // the Free Software Foundation, either version 3 of the License, or
    7 // (at your option) any later version.
    8 // 
    9 // Cnetbench is distributed in the hope that it will be useful,
   10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
   11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   12 // GNU General Public License for more details.
   13 // 
   14 // You should have received a copy of the GNU General Public License
   15 // along with cnetbench.  If not, see <http://www.gnu.org/licenses/>.
   16 // 
   17 #include "common.h"
   18 
   19 //
   20 // Watches an array of pids for their exit, and updates the output array
   21 // exit_times with each pid's exit timeval struct timestamp (epoch with
   22 // microseconds).
   23 //
   24 // Note that this function does not start the pids, but only watches them. To
   25 // calculate runtime, external code needs to track when the pids were created.
   26 //
   27 // @param pids       Array of pid_t pids to be watched
   28 // @param count      Number of pids in the pids array
   29 // @param exit_times Array of timeval structs that will contain exit times for
   30 //                   all of the pids in the array. Must be at least the size of
   31 //                   the pids array or unpredictable behavior may result.
   32 //
   33 // @return int Overall status of all exited pids (if any fail exit, returns 1)
   34 //
   35 int time_pids(pid_t* pids, int count, struct timeval *exit_times) {
   36   int i;
   37   int waiting = 1;
   38 
   39   while(waiting != 0) {
   40     waiting = 0;
   41     for(i = 0; i < count; i++) {
   42       // Pid with this index has exited, skip it.
   43       if(pids[i] == 0)
   44         continue;
   45 
   46       // 0 = state change (exit)
   47       if(waitpid(pids[i], NULL, WNOHANG) != 0) {
   48         // Child has exited
   49         pids[i] = 0;
   50         // Write the exit time
   51         gettimeofday(&exit_times[i], NULL);
   52       } else {
   53         waiting = 1;
   54       }
   55     }
   56     sleep(1);
   57   }
   58   return 0;
   59 }

Generated by cgit