The task here is :This is basic C program which must contains two processes.First one writes in a file 60 random numbers.The seconds that needs to be written has to read the file and write only the even number into another new file.So I have this code and the parent process that needs to write the even numbers to a file its not working properly.Also my question is about the structure of the code.Is this the best way to describe the processes.
#include <stdio.h>
#include <fcntl.h>
int main() {
int pid, fd, buf, i, fd2, buf2;
pid = fork();
switch (pid) {
case 0: {
printf("\n Child process is writing numbers. \n");
fd = open("file.dat", O_RDWR | O_CREAT, 0644);
for (i = 0; i < 60; i++) {
buf = rand() % 20 - 10;
printf("\n Writing number %d %d ", i + 1, buf);
write(fd, &buf, sizeof(buf));
}
close(fd);
break;
}
case -1: {
printf("\n Fork error! \n");
}
default: {
wait(pid);
printf("\n Parent process is Copying numbers. \n");
fd = open("file.dat", O_RDONLY);
fd2 = open("file_output.dat", O_RDWR | O_CREAT, 0644);
while (read(fd, &buf, sizeof(buf)) == sizeof(buf)) {
if (buf & ~1)
(buf2 = buf);
write(fd2, &buf2, sizeof(buf2));
printf("Writing number in file_output.dat %d \n", buf2);
}
close(fd2);
close(fd);
}
}
return 0;
}
Your condition is wrong:
You write the number out regardless, but if it’s odd (excepting that you need to fix the even/odd test) then you don’t update
buf2. If the first number is odd,buf2is uninitialised.You need this:
Note that this might not correctly test negative even numbers. You could test
abs(buf) % 2 != 0. The only number that might not be handled would beINT_MIN.