操作系統:Linux,語言:純Cprintf的異常「fork()的」
我在一個特殊的情況下UNIX下學習一般C編程和C編程前進。
在使用fork()
調用之後,我檢測到printf()
函數的一個奇怪的(對我來說)行爲。
代碼
#include <stdio.h>
#include <system.h>
int main()
{
int pid;
printf("Hello, my pid is %d", getpid());
pid = fork();
if(pid == 0)
{
printf("\nI was forked! :D");
sleep(3);
}
else
{
waitpid(pid, NULL, 0);
printf("\n%d was forked!", pid);
}
return 0;
}
輸出
Hello, my pid is 1111
I was forked! :DHello, my pid is 1111
2222 was forked!
爲什麼第二個 「你好」 字符串出現在孩子的輸出?
是的,這正是母公司開始時打印的父母的pid
。
但是!如果我們在每個字符串的結尾放置\n
字符,我們得到了預期的輸出:
#include <stdio.h>
#include <system.h>
int main()
{
int pid;
printf("Hello, my pid is %d\n", getpid()); // SIC!!
pid = fork();
if(pid == 0)
{
printf("I was forked! :D"); // removed the '\n', no matter
sleep(3);
}
else
{
waitpid(pid, NULL, 0);
printf("\n%d was forked!", pid);
}
return 0;
}
輸出:
Hello, my pid is 1111
I was forked! :D
2222 was forked!
它爲什麼會發生?這是正確的行爲,還是它的錯誤?
好吧,我明白了。但是我仍然無法向自己解釋爲什麼「緩衝垃圾」出現在孩子輸出中新打印行的末尾? 但是等等,現在我懷疑它確實是CHILD的輸出。哦,你能解釋爲什麼輸出看起來像這樣,一步一步地完成(新字符串),所以我會非常感激。 無論如何謝謝你! – pechenie 2010-03-28 06:40:09
非常令人印象深刻的解釋!非常感謝,終於明白了! P.S .:我先前給你投了一個票,現在我再次愚蠢地點擊了「向上箭頭」,所以投票消失了。但我不能再給你了,因爲「答案太舊了」:( P.P.S .:我給了你一個其他問題的投票,並且再次感謝你! – pechenie 2010-03-28 17:43:25