之間的資源爭奪以下是我的測試代碼:如何看父進程和子進程
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
pid_t pid;
/* create first child process */
pid = fork();
if (pid < 0) {
perror("fork error");
exit(1);
}
if (pid > 0) { // parent process
pid = fork();
if (pid < 0) {
perror("fork error");
exit(1);
}
if (pid > 0) { // parent process
for (int i = 0; i < 100; i++) {
printf("aaaaaaaaaaa\n");
}
} else { // second child process
for (int i = 0; i < 100; i++) {
printf("cccccccccc\n");
}
}
} else { // first child process
for (int i = 0; i < 100; i++) {
printf("bbbbbbbbbb\n");
}
}
exit(0);
}
三個過程將內容傳遞給printf到標準輸出,但我每次運行的時間代碼,事實證明,三個進程一個一個地運行,我看不到我期望的輸出。我知道這是因爲CPU速度太快,幾乎不可能看到我期望的輸出。所以我寫了另一個程序這是一個死循環,就像這樣: while(1){ i ++; } 使CPU使用率高,但我仍然看不到我期望的輸出。 我能做什麼?
你可以發佈輸出..? – akp
@akp,輸出如下:100行aaaaaaaaaa \ n,然後遵循100 bbbbbbbbbb \ n,然後遵循100 cccccccccc \ n。我期望的輸出是三個部分相互混合。可能是這樣的: 60行aaaaaaaaaa \ n,100行bbbbbbbbbb \ n,50行cccccccccc \ n,40行aaaaaaaaaa \ n,50行cccccccccc \ n。但CPU看起來太快了,我看不到這樣的輸出 – haipeng31
ur代碼工作正常,它在我的系統上產生隨機輸出...我認爲這只是由於fst CPU ... – akp