這是我的代碼C++的隨機數,等待父母所有的孩子當過程
#include <iostream>
#include <string>
#include <ctime>
int main()
{
for (int i=0;i<3;i++) {
if((pid()==fork())==0){
break;
}
}
if(pid==0) {
// son process
srand(time(NULL));
int r = rand()%4+1;
cout<<"pid:"<<getpid() <<"num": "<<r<<endl;
}
else{
//parent process
}
}
我有問題trandom數相同的全部過程,我怎麼可以重置蘭特()? 我已經試圖做不同的srand()到每個進程它不起作用。
'如果((PID()==叉())== 0)' - 這個構造很有趣......我懷疑這個代碼將編譯。 –
如果你想讓它們得到不同的隨機數,你需要在每個進程中給'srand()'一個不同的參數。由於所有進程同時啓動,'time(NULL)'將是相同的。 – Barmar
你應該只問一個問題,而不是3個不同的問題。 – Barmar