gpt4 book ai didi

c - C (POSIX) 中的 sleep 函数破坏了我的程序

转载 作者:行者123 更新时间:2023-12-04 12:35:38 25 4
gpt4 key购买 nike

这是我的程序代码:

#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>

void function() {
srand(time(NULL));
while(1) {
int n = rand();
printf("%d ", n);
//sleep(1);
}
}

int main() {
pid_t pid;

pid = fork();
if (pid == 0) {
function();
}
}

在 sleep 行被注释掉(如上面的代码)后,程序运行良好(即它打印一堆随机数太快,甚至看不出它们是否真的是随机的),但如果我删除注释程序不会'打印任何内容并退出(甚至不是第一次,在它进入休眠状态之前),即使它编译时没有警告或错误,有或没有评论。

最佳答案

but if I remove the comment the program doesn't print anything and exits

它不打印,但也不真正退出。它仍然会在后台运行一个进程。该过程会运行您的无限 while 循环。

p.c 中使用您的代码:

$ gcc p.c 

$ ./a.out

$ ps -A | grep a.out
267282 pts/0 00:00:00 a.out

$ killall a.out

$ killall a.out
a.out: no process found

问题是 printf 并没有真正打印出来。它只将数据发送到输出缓冲区。为了强制打印输出缓冲区,调用 fflush(stdout)

如果您不刷新,那么您只需依赖您正在使用的终端的行为。当您将换行符写入输出流时,终端刷新是很常见的。这就是为什么最好使用 printf("data\n") 而不是 printf("\ndata") 的原因之一。有关详细信息,请参阅此问题:https://softwareengineering.stackexchange.com/q/381711/283695

我怀疑如果您让程序继续运行,它最终会打印出来。它有一个有限的缓冲区并且在缓冲区满时刷新是有道理的。但这只是一个(有根据的)猜测,它取决于您的终端。

it prints a bunch of random numbers too fast to even see if they are actually random

如何判断数字序列是否随机? (唱反调)

关于c - C (POSIX) 中的 sleep 函数破坏了我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65267018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com