日期:2014-05-16  浏览次数:20704 次

fork 出来的多个子进程 怎么样能 wait 不同的时间
C/C++ code


#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <string.h>
#include <time.h>

using namespace std;

int main()
{
    srand(time(NULL));
    int status,i;
    pid_t apid;
    for (i = 0; i < 10; i++)
    {
        status = fork();
        if (status == 0 || status == -1) break;
    }
    if (status == -1)
    {
        //error
        cout << "error" << endl;
    }
    else if (status == 0)
    {
        //sub process


        pid_t cpid;
        cpid = getpid();
        cout << "in child " << i <<" pid= "<< cpid << endl;
        int msec;
        msec = rand()%1000000;
        usleep(msec);
        exit(0);
    }
    else
    {
        //parent process
        apid=wait(&status);
        cout << "apid= " << apid << endl;
    } 
    
    return 0;
}







按照上面的程序 我想让每一个子进程 在输出自己的 pid和顺序之后 都随机停止一段时间。
这样 wait()得到的 返回子进程的 pid就不会总是第一个了


但是实际情况是 在输出所有pid 和 i之后 程序才停止。。 
wait 返回的pid总是第一个fork出来的 子进程pid  

怎么能解决?

------解决方案--------------------
楼主还不明白rand的用法
C/C++ code

#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <string.h>
#include <time.h>

using namespace std;

int main()
{
    srand(time(NULL));
    int status,i;
    pid_t apid;
    for (i = 0; i < 10; i++)
    {
        status = fork();
        if (status == 0 || status == -1) break;
    }
    if (status == -1)
    {
        //error
        cout << "error" << endl;
    }
    else if (status == 0)
    {
        //sub process


        pid_t cpid;
        cpid = getpid();
        cout << "in child " << i <<" pid= "<< cpid << endl;
        int msec;

        // Add the following three lines
        time_t tick;
        tick = time(0);
        srand((tick << 16) | (getpid() & 0xffff));

        msec = rand()%1000000;

        // Add the following line to check the msec
        cout << "msec = " << msec << endl;

        usleep(msec);
        exit(0);
    }
    else
    {
        //parent process
        apid=wait(&status);
        cout << "apid= " << apid << endl;
    } 
    
    return 0;
}