/* -----------------------------------------
usage:
  % gcc -O3 rcutest.c -o rcutest
  % N=`grep -c processor /proc/cpuinfo`
  % ./rcutest ${N}
  Copyright: KaiGai <kaigai@ak.jp.nec.com>
----------------------------------------- */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#define LOOP     (5000000)

void child_shmfile(){
  int i,fd;
  char buf[100],fname[100];
  
  sprintf(fname,"/dev/shm/file.%d",getpid());
  
  fd = open(fname,O_RDWR|O_CREAT|O_TRUNC);
  if( fd < 0 ){
    printf("NOTE: Process(%d) can not open %s",getpid(),fname);
    return;
  }
  
  for(i=0;i<LOOP;i++){
    write(fd,buf,1);
    lseek(fd,0,SEEK_SET);
  }
  
  unlink(fname);
}

int main(int argc, char *argv[]){
  int fd,i,j,cproc,nproc;
  int sec,usec;
  struct timeval stm,etm;
  
  if( argc!=2 )
    return( 1 );
  nproc = atoi(argv[1]);
  
  gettimeofday(&stm, NULL);
  for(i=0,cproc=0;i<nproc;i++){
    j = fork();
    if( j==0 ){
      child_shmfile();
      exit( 0 );
    }else if( j>0 ){
      cproc++;
    }
  }
  waitpid(-1,NULL,0);
  gettimeofday(&etm, NULL);

  sec = etm.tv_sec - stm.tv_sec;
  usec = etm.tv_usec - stm.tv_usec;
  if( usec<0 ){
    sec--;
    usec = 1000000 + usec;
  }
  printf("[%d Proc x %d Loop] Time: %.4f \n",cproc,LOOP,
	 (double)sec + ((double)usec)/10000000.0 );
}

