考慮以下程序的輸出:混淆叉的輸出要求
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
void main()
{
pid_t pid;
int a = 5;
pid = fork();
if (pid == 0)
printf("This is the son process, a = %d\n", --a);
else
printf("This is the dad process, a = %d\n", ++a);
}
,我期望的輸出是:
This is the son process, a = 4;
This is the dad process, a = 6;
但我得到的輸出:
This is the son process, a = 4
那麼爲什麼父進程沒有執行printf?我怎樣才能得到我想要的輸出?
更新:
剛纔我試了一次,這樣的輸出:
$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
$ This is the son process, a = 4
現在還有一個問題:爲什麼會出現輸出的線$
兩者之間?
我認爲預期的輸出應該是這樣的:
$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
This is the son process, a = 4
我想不通爲什麼$
是存在的。
更多細節:
gcc version: gcc 4.8.2
OS: ubuntu 14.04
複製粘貼你的代碼,我得到你期望的輸出。我建議你指定你正在編譯/運行哪個操作系統。 – m0skit0
我無法重現這一點。但是你需要'#include'(而不是pthread.h,這裏不需要pthread.h)。如果它仍然不起作用,您應該發佈更多信息,例如編譯和運行程序的方式以及您正在使用的平臺。 –
nos
從兒子printf工作,但它是從父親的printf沒有工作......你肯定需要指定你的環境 – theadnangondal