Search code examples
csleep

Sleep system call ,What is the default sleep time?


What is the default sleep time if we don't pass any arguments to sleep( ) function?

#include<stdio.h>
int main()
{
    int pid,dip,cpid;
    pid = fork();
    if (pid == 0)
    {
        printf("\n first child is created %d",getpid());
    }
    else
    {
        dip = fork();
        if (dip == 0)
        {
            printf("\n second process is creatred %d",getpid());
        }
        else
        {
            sleep();
            cpid = wait(0);
            printf("\n child with pid %d  ", cpid);
            cpid = wait(0);
            printf("\n child with pid %d  ",cpid);
            printf("\n I am parent \n");
        }
    }
}

What is the output of the above code?


Solution

  • You should not call a function (including sleep) which has not been declared. According to the sleep(3) man page, you should #include <unistd.h>; on my Linux/Debian system /usr/include/unistd.h declares:

     extern unsigned int sleep (unsigned int __seconds);
    

    If you don't declare a function (this is bad habit; Use gcc with -Wall -Wmissing-prototypes to be warned) it has unspecified arguments and int result.

    If you did (like you should) #include <unistd.h> your code won't even compile (the call to sleep without arguments would be marked as error).

    In practice, your sleep call is invoked with whatever garbage value is in the register used to pass the first argument. This is typical undefined behavior, and you cannot predict that value, and you should be scared.

    So there is no default sleep time, and stricto sensu your question makes no sense. Check by reading the C11 standard n1570 and the POSIX standards.