gpt4 book ai didi

C fork : child proc-meant printf messages appear only after the whole program finishes

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:50 24 4
gpt4 key购买 nike

得到这段代码:

static void
prime_test(void)
{
fprintf(stdout, "child prime_test process started\n");
int num;
fprintf(stdout, "enter your num: ");
fscanf(stdin, "%d", &num);
fprintf(stdout, "you entered %d\n", num);
if (num == -1) {
fprintf(stdout, "-1 is the wrong value\nnow exiting prime_test...\n");
exit(1);
}
int i;
int count = 0;
fprintf(stdout, "processing numbers...\n");
for (i = 1; i <= num; i++) {
if (num % i == 0) {
count++;
fprintf(stdout, "%d divides %d\n", i, num);
}
}
fprintf(stdout, "---------------------\n");
fprintf(stdout, "%d has %d divisors\n\n", num, count);
sleep(1);
}

int
main(void)
{
system("clear");
fprintf(stdout, "main() started\n");
while (1) {
pid_t pid = fork();
switch (pid) {
case -1:
fprintf(stderr, "failed to fork\n");
exit(1);
case 0:
fprintf(stdout, "now in child\n");
prime_test();
break;
case 1:
fprintf(stdout, "now in parent\n");
break;
}
if (pid != 0) {
int child_status;
pid_t child_pid = wait(&child_status);
fprintf(stdout, "child process with pid=%d finished\n", child_pid);
if (WIFEXITED(child_status)) {
fprintf(stdout, "child process with pid=%d exited with code %d\n", child_pid, child_status);
break;
}
}
sleep(1);
}
return 0;
}

我打印除数,直到用户输入 (-1)。如果 -1 我退出。它工作正常!我的问题是我想让 if (pid != 0) 中的消息在我退出 prime_test() 后立即出现。但它们只有在我输入 -1 退出整个程序后才会出现。

最佳答案

想要的不一定是可能发生的。在 block if( pid != 0) 中,您使用了 wait()。这意味着您将阻塞父线程,直到子线程完成执行。这些语句还打印出 child 完成执行并打印退出代码。从逻辑上讲,您只能在线程完成后打印退出代码。

现在,如果您想从父进程打印一些东西,以了解父进程正在并发执行,我建议添加 fprintf(stdout,"Parent process waiting for child to complete..."); wait() 函数之前。

关于C fork : child proc-meant printf messages appear only after the whole program finishes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33279795/

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