c ++随机数并在进程时等待所有子进程的父进程

时间:2017-04-13 15:49:17

标签: c++ c process

这是我的代码

    #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编号与所有进程相同,我如何重置rand()?  我已经尝试为每个进程设置不同的srand()。

1 个答案:

答案 0 :(得分:0)

  1. time(NULL)+getpid()放入所有兰特的不同种子;
  2. http://man7.org/linux/man-pages/man3/pthread_join.3.html