bronze56k
bronze56k

Reputation: 55

Using wait and signals to make father proccess wait for childs to end

I have an assignment where i need to create a father process and 2 child proccess that have the same father, the first child process need to read a string and print it console, the second child process need to read another string and print it in console and the father needs to concatenate these 2 strings and print it in console as well. It seems simple but im having a rough time with the wait and signals part somehow i cant make the father wait for the childs proccess first so he can act.

#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
char papa[1000]; 
char hijo1[100];
char hijo2[100];


int main () {
pid_t son1,father;
int status;
son1 = fork();

if (son1 == 0) {            //proceso hijo 1
    printf("hijo1:%d\n", getpid());
    fgets(hijo1, 100, stdin);
    printf ("%s\n", hijo1);
sleep(2);
exit (0);
}else if (son1 > 0) {           //proceso padre

    pid_t son2 = fork();

    if (son2 == 0) {        //proceso hijo 2

printf("hijo2:%d\n", getpid());


exit (0);
}else if (son2 > 0) {
    wait(NULL);
    printf("padre:%d\n", getpid());
sleep(2);   
exit (0);
}else {
    printf("fork error");
    return 0;
    }
  } else {
    printf("fork error");
    return 0;
  }

 return 0;
}

this is just the structure while i find the way of making process father wait

Upvotes: 1

Views: 64

Answers (1)

P.P
P.P

Reputation: 121387

I'll give just some hints using which you could put it all together.

  • Forget about signals - it's an overkill. You don't need to use signals at all for this task.

  • Parent and child processes do not share address spaces. Parent process can only retrieve the exit status of child not the strings that you want. So how are you going to get the strings from the child? You need to use one of the IPC techniques.

  • For the communcation (to send strings from child processes to parent), I suggest you look at the pipe example from glibc documentation. The example shows only one child process. You need to think how you can extend it for multiple processes.

Upvotes: 1

Related Questions