c - sleep 系统调用,默认 sleep 时间是多少?

标签 c sleep

如果我们不向 sleep( ) 函数传递任何参数,默认 sleep 时间是多少?

#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");
        }
    }
}

上面代码的输出是什么?

最佳答案

您不应调用尚未声明的函数(包括 sleep )。声明。根据sleep(3)手册页,你应该 #include <unistd.h> ;在我的 Linux/Debian 系统上 /usr/include/unistd.h声明:

 extern unsigned int sleep (unsigned int __seconds);

如果你不声明一个函数(这是坏习惯;使用 gcc with -Wall -Wmissing-prototypes 来警告)它有未指定的参数和 int结果。

如果你这样做了(就像你应该做的那样)#include <unistd.h>您的代码甚至无法编译(不带参数调用 sleep 将被标记为错误)。

实际上,您的sleep使用用于传递第一个参数的寄存器中的任何垃圾值来调用调用。这是典型的undefined behavior ,并且您无法预测该值,您应该是 scared .

所以没有默认的 sleep 时间,严格意义上你的问题没有意义。通过阅读C11标准n1570进行检查和 the POSIX 标准。

关于c - sleep 系统调用,默认 sleep 时间是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52034996/

相关文章:

c++ - 如何在程序执行期间防止屏幕保护程序和 sleep ?

c - 下面的代码段有什么问题?

objective-c - CGContextFillRects 与 CGContextAddLineToPoint(矩形与线条)性能

xcode - Mac 从 sleep 状态恢复时会触发什么事件?

c++ - 每 1 秒调用一个函数(精确地)

c++ - 进程启动前窗口不弹出 -> 尝试了 sleep() 方法,但是 "fails"

.net - .net 中的高精度休眠/等待

c - 为什么结构数组允许我索引到边界数组之外

c - 为什么 '\97' ascii 值等于 55

c - recvmsg() 返回 "Resource temporarily unavailable"