一个人如何创建一个分叉并继续而不等待另一个完成?我编写了一个示例程序来说明我的问题。
该程序有一个计数程序,它只是从零开始计数,并每秒连续打印下一个数字。这是程序的父端,客户端坐在那里不断地等待用户输入。当用户输入一个数字时,计数变成这个数字,因为变量是共享的。这是代码
#include <sys/time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h> // Declaration for exit()
using namespace std;
struct Timer {
int GetTimeMilli()
{
gettimeofday( &end,NULL);
return int( (end.tv_sec - start.tv_sec )*1000) +
int( (end.tv_usec-
start.tv_usec)/1000);
}
Timer()
{
ResetTimer();
}
//reset timer so start time becomes current time
void ResetTimer()
{
gettimeofday( &start,NULL);
}
private:
struct timeval start, end;
};
int num = 0;
int main()
{
char* name = new char[256];
pid_t pID = vfork();
if (pID == 0) // child
{
// Code only executed by child process
printf( "child process: \n");
while(1)
{
cin.getline( name,20 );
num = atoi( name);
}
}
else if (pID < 0) // failed to fork
{
cerr << "Failed to fork" << endl;
exit(1);
// Throw exception
}
else // parent
{
// Code only executed by parent process
printf( "parent process:\n");
Timer a;
while(1)
{
if( a.GetTimeMilli() > 1000.0f )
{
a.ResetTimer();
printf("%d\n",num);
num++;
}
}
}
// Code executed by both parent and child.
delete[] name;
return 0;
}