'm creating a small guess game between a child and a parent:
The child takes in the input from user and makes that the number to guess, the parent simply goes into a loop trying to figure out which is the right number.
I can't get it to work fully. Also you can see I'm keeping track of how many times it takes, once its found, make a new one and then exits after 4 rounds.
Code:#include <stdio.h> #include <unistd.h> #include <time.h> #include <stdlib.h> char readbuffer[100]; int main() { int pid, nbytes, i, input; int fd[2] = {} ; int guess = 0; pid = fork(); int x; srand((unsigned) time(NULL)); x = (rand() % 10 + 1); if (pid == 0) { close(fd[0]); printf("enter a number "); scanf("%d", &input); write(fd[1], &input, (sizeof(input))); if (x == input) { exit(0); } close(fd[1]); } else { //PARENT close(fd[1]); nbytes = read(fd[0], &input, sizeof(input)); while (x != input) { if (x != input) { guess++; } } char answer; if (x == input) { printf(" correct"); printf("Number of Guesses: %d\n", guess); exit(0); } //to reset random x = (rand() % 10 + 1); close(fd[0]); } }




Reply With Quote
