fork 出来的多个子进程 怎么样能 wait 不同的时间
#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;}
#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;}