0

I have the following function where I try to get an input from a user through the child process then get a random number from the parent process. After getting the random number from the parent process I would like to get another input from the child process. I tried using wait but the program just terminates anyway, is there any other way for me to go about this?

int main() {
    int val, status; 
    int pid = fork();

    if (pid > 0) {
        srand(time(NULL));
        int randNo = rand() % (100+ 1 - 0) + 0; 
        sleep(5);
        printf("%d\n", randNo);
    } else if (pid == 0) {
        printf("Enter a value between 0 and 100: ");
        scanf("%d", &val);
    } else{ 
        perror("fork");
        exit(1);
    }
}
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 1
    Possible duplicate of [fork() and pipes() in c](https://stackoverflow.com/questions/4812891/fork-and-pipes-in-c) – GalAbra Aug 04 '18 at 16:44
  • The techniques for coordinating behavior of separate processes, such as your parent and child processes, fall under the umbrella of "inter-process communication". There is a fair variety of such techniques, but the one I would suggest is to use `pipe`s, especially if you have in mind to communicate the scanned or computed numbers between processes. You can find lots of information about that on the web, including in many SO questions answers. – John Bollinger Aug 04 '18 at 16:45
  • 1
    Calling `pipe()` before you fork will give you a pair of file descriptors - one that the parent can write into and one that the child can read from. – John Hascall Aug 04 '18 at 17:52

0 Answers0