Home > Blockchain >  Duration of child process sleep
Duration of child process sleep

Time:09-15

Is it possible to determine in Linux as a parent process how much time a child process sleeps, whenever it sleeps using the nanosleep() system call?

Thanks!

CodePudding user response:

You can wrap glibc:

% gcc -fPIC -shared -o nanosleep.so nanosleep.c -ldl
% export LD_PRELOAD=/path/to/your/nanosleep.so /path/to/app/using/test

Wrapper code nanosleep.c:

#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

int (*real_nanosleep)(const struct timespec *req, struct timespec *rem) = NULL;

/* wrapping nanosleep function call */
int nanosleep(const struct timespec *req, struct timespec *rem)
{
    printf("How much %d us\n", req->tv_nsec);

    /* Fetch the real nanosleep function from glibc */
    real_nanosleep = dlsym(RTLD_NEXT, "nanosleep");
    return real_nanosleep(req, rem);
}

Test program test.c:

#include <stdio.h>
#include <time.h>

int main () {
   struct timespec req = {0}, rem = {0};
   req.tv_sec = 2;
   req.tv_nsec = 1000000000;
   nanosleep(&req, &rem);
   return(0);
}
  • Related