[英]fork() and stderr with terminal
我使用 fork() 來運行不同的進程並打印一條簡單的消息。代碼的結果雖然讓我感到困惑.. 看看代碼:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <math.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <time.h>
int main(void)
{
fork();
fork();
fork();
fprintf(stderr,"hello world\n");
}
輸出是:
mario@ubuntu:~/OS$ ./main
hello world
hello world
hello world
hello world
hello world
hello world
mario@ubuntu:~/OS$ hello world
hello world
mario@ubuntu:~/OS$
請注意,我在終端的第一行執行程序,但輸出不是我所期望的。 請幫我! 提前致謝! 如果 fprintf 用 printf("......") 改變,同樣的事情會發生
編輯:我不明白為什么打印是這樣的。 終端線前 6 行,旁邊 1 行,后 1 行......
當父程序退出時,運行父程序的shell在屏幕上打印shell提示符mario@ubuntu:~/OS$
。 任何尚未打印它的hello world
的子程序都將在提示后打印。 如果您希望提示不在所有hello world
之前出現,您需要讓父程序等待所有子程序和孫子程序終止。
檢查這個以了解如何讓父母等待。
您正在創建 8 個進程。 每個fork
將進程分成兩個。 如果原始父進程完成了我仍在執行的其他進程。 因此,如果原始進程完成執行,則盡管其他進程仍在執行,shell 仍會執行並打印提示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.