-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMasterSlave.c
More file actions
79 lines (72 loc) · 1.89 KB
/
MasterSlave.c
File metadata and controls
79 lines (72 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/file.h>
void slave(int row, int column, int array[row][column], FILE *file);
void parent();
int main(int argc, char* argv[]) {
int row = atoi(argv[1]); // New addition
int column = atoi(argv[2]); // New Addition
int val = atoi(argv[3]); // New Addition
if (remove("somefile2.txt") != 0)
printf("Error removing file.");
else
printf("File remove succesfully.");
FILE *somefile; // New Add
somefile = fopen("somefile2.txt","a"); // New Add
pid_t pid;
int i=0,j,k,l=0;
int array[row][column];
for (j=0;j<row;j++) {
for (k=0;k<column;k++) {
array[j][k] = val;
}
}
for (i;i<row;i++) {
if ((pid = fork()) == 0)
slave(i,column,array,somefile);
else
parent();
}
return 0;
}
void slave(int row, int column, int array[row][column],FILE *some) { /*Child function splits the array into rows and*/
int k,l,sum=0,lockt; /*individually adds up the sum of the rows when it is called*/
FILE* file=some;
for (k=0;k<column;k++) {
sum += array[row][k];
printf("%d\n",sum);
}
printf("I am the slave.\n");
//file = fopen("somefile2.txt","a");
fprintf(file,"%d\n",sum);
fclose(file);
exit(0);
return;
}
void parent() { /*Adds up total using the results from child*/
FILE* newfile;
char *a; int i,total; char buffer[1024]; int newbuf;
newfile = fopen("somefile2.txt","r");
while ( fgets(buffer,1024,newfile) > 0 ) {
sscanf(buffer,"%d",&newbuf);
printf("%d\n",newbuf);
}
fclose(newfile);
printf("I am the parent.\n");
}
char* child_reverse_string(char *string) {
int end= strlen(string)-1;
int start = 0;
while(start<end)
{
string[start] ^= string[end];
string[end] ^= string[start];
string[start]^= string[end];
++start;
--end;
}
return string;
}