[問題] 關於srand(time(NULL))應用於多process
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>
int main(){
int n1=0,n2=0;
pid_t pid;
pid=fork();
if(pid==0){
srand(time(NULL));
//child
n1=rand()%10;
printf("n1:%d\n",n1);
exit(-1);
}//end if
else{
srand(time(NULL));
//parent
n2=rand()%10;
printf("n2:%d\n",n2);
wait();
}//end else
}//end main
上述code中,印出來的n1 以及 n2每次都相等
可是我就是希望他有時候不一樣,
回溯原因我想可能是出在srand(time(NULL))吧!
可是既然已經fork了
竟然發現兩個process的time(NULL)每次取的值都一樣
這是因為現在multi-processor的關係嗎?
想要讓兩個process time(NULL)取的值不同該怎麼做呢?
感謝大家~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.68.5
※ 編輯: sandybright 來自: 140.113.68.5 (10/18 15:07)
→
10/18 16:14, , 1F
10/18 16:14, 1F
→
10/18 16:18, , 2F
10/18 16:18, 2F
推
10/18 16:21, , 3F
10/18 16:21, 3F
→
10/18 16:21, , 4F
10/18 16:21, 4F
→
10/18 16:22, , 5F
10/18 16:22, 5F
→
10/18 16:23, , 6F
10/18 16:23, 6F
→
10/18 16:23, , 7F
10/18 16:23, 7F
→
10/18 16:23, , 8F
10/18 16:23, 8F
→
10/18 16:51, , 9F
10/18 16:51, 9F
→
10/18 16:53, , 10F
10/18 16:53, 10F
→
10/18 16:53, , 11F
10/18 16:53, 11F
→
10/18 16:53, , 12F
10/18 16:53, 12F
→
10/18 16:53, , 13F
10/18 16:53, 13F
→
10/18 16:56, , 14F
10/18 16:56, 14F
→
10/18 16:57, , 15F
10/18 16:57, 15F
→
10/18 16:57, , 16F
10/18 16:57, 16F
→
10/18 16:58, , 17F
10/18 16:58, 17F
→
10/18 16:59, , 18F
10/18 16:59, 18F
推
10/18 17:13, , 19F
10/18 17:13, 19F
→
10/18 17:13, , 20F
10/18 17:13, 20F
→
10/18 17:26, , 21F
10/18 17:26, 21F
→
10/18 17:27, , 22F
10/18 17:27, 22F
推
10/18 17:49, , 23F
10/18 17:49, 23F
→
10/18 17:49, , 24F
10/18 17:49, 24F
推
10/18 17:55, , 25F
10/18 17:55, 25F
推
10/18 17:58, , 26F
10/18 17:58, 26F
→
10/19 01:16, , 27F
10/19 01:16, 27F
→
10/19 01:23, , 28F
10/19 01:23, 28F
→
10/19 09:36, , 29F
10/19 09:36, 29F
推
10/20 01:49, , 30F
10/20 01:49, 30F
推
10/23 00:13, , 31F
10/23 00:13, 31F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章