フォークを作成し、他のフォークが完了するのを待たずに続行するにはどうすればよいですか? 私の問題を説明するためにサンプル プログラムを作成しました。
このプログラムには、ゼロからカウントアップし、毎秒連続して次の数字を出力するカウントプログラムがあります。これはプログラムの親側であり、クライアントはユーザーの入力を継続的に待機します。ユーザーが数値を入力すると、変数が共有されているため、カウント数はこの数値になります。ここにコードがあります
#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;
}