Hi Guys,
I am working on developing a simulation program that tracks multiple vehicles entered by the user and copy the current location of that vehicle in the specified text file.
For example,
If the user inputs 3 then the program must generate 3 text files for each vehicle and then using the simulation program locations are saved in the text file.
The problem:
I created the simulation program for one vehicle that successfully saves the location of that vehicle but I want the program to simulate multiple vehicles simultaneously using threads.
So each vehicle is considered as a thread and it has it's own text file.
Hope it's clear:)
The code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#include <pthread.h>
int main()
{
FILE *file;
int v = 0;
int i;
int x, y;
int mode ;
srand ( time(NULL) );
printf("===============================================\n");
printf("====Simulation Program For Testing Tracking====\n");
printf("===============================================\n");
printf("Please enter the number of vehicles you want to track: \n");
scanf("%d",&v);
printf("The %d vehicle(s) are being simulated...\n",v);
int index,select=0;
printf("Please Choose Which vehicle to Track From the List Below:\n");
for(index=1;index<=v;index++)
{
printf("%d. vehicle%d.\n", index,index);
}
printf("Enter the number of the vehicle only: ");
scanf("%d",&select);
int place=select;
int trial=0;
int Xcor[50];
int Ycor[50];
Xcor[0]=Ycor[0]=0;
for(i=1; i<=50; i++)
{
if(i<=24){
Xcor[i]=Xcor[i-1] + 2;
Ycor[i]=Ycor[i-1] + 2;
}
else
{
Xcor[i]=Xcor[i-1] - 1;
Ycor[i]=Ycor[i-1] - 1;
}
}
pid_t pid;
pid = fork();
if(pid == -1) //Checking for error in forking "Spawn"
printf("Bad Fork...Try Again\n");
else if(pid == 0)
{
while (trial!=10)
{
mode = rand() % 50;
x=Xcor[mode];
y=Ycor[mode];
file = fopen("1.txt","w");
if (!file) {
printf("Error in opening file");
}
fprintf(file,"XLocation=%d&YLocation=%d",x,y);
printf("The Location of vehicle%d is: ( %d , %d )\n",place,x,y);
fclose(file);
sleep(1);
trial++;
}
}
return 0;
}
Any help is appreciated.