/*
 * © Copyright 1996-2012 ECMWF.
 * 
 * This software is licensed under the terms of the Apache Licence Version 2.0
 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
 * In applying this licence, ECMWF does not waive the privileges and immunities 
 * granted to it by virtue of its status as an intergovernmental organisation nor
 * does it submit to any jurisdiction.
 */

#include "mars.h"

err locked_write(const char *fname, char *str, long len);

int main(int argc, char **argv)
{
	char *fname = argv[1];
	int n = 0;
	char strpid[1024],content[1024];
	long w = getpid()%100000;
	long pid = getpid();
	long max = 100;
	time_t now;

	if(argc > 2)
		max = atol(argv[2]);
	
	sprintf(strpid,"%d",getpid());
	sprintf(content,"%s\n",strpid);
	argv[0] = "mars";
	argv[0] = strpid;
	marsinit(&argc,argv,NULL,0,NULL);

	for(n = 0; n<max; n++)
	{
		if(locked_write(fname,content,strlen(content)) == 0)
			marslog(LOG_INFO,"file locked %d times, waiting %ld microsec",n,w);
		else
			marslog(LOG_EROR|LOG_PERR,"Error while locked_write(%s)",fname);
		time(&now);
		w = (n*pid*now)%1000000;
		if(w)
			usleep(w);
	}

	marslog(LOG_INFO,"exit");
	exit(0);
}

