Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAX_CHILDREN 3
- int main(int argc, char *argv[])
- {
- pid_t pid;
- int fd[2];
- char buffer[100];
- char str[] = "Hello";
- char str2[] = "Hello2";
- char str3[] = "Hello3";
- for(int num_process = 0; num_process < MAX_CHILDREN; num_process++)
- {
- if(pipe(fd) == -1)
- {
- perror( "pipe Failed" );
- continue;
- }
- pid = fork();
- if(pid < 0)
- {
- perror("fork failed");
- exit(1);
- }
- if(pid == 0)
- { //child code
- if(num_process == 0){
- printf("Child %i (pid= %i) send string %sn", num_process, getpid(),str);
- write(fd[1],str,strlen(str));
- }
- if(num_process == 1){
- printf("Child %i (pid= %i) send string %sn", num_process, getpid(),str2);
- write(fd[1],str2,strlen(str2));
- }
- if(num_process == 2){
- printf("Child %i (pid= %i) send string %sn", num_process, getpid(),str3);
- write(fd[1],str3,strlen(str3));
- }
- exit(0);
- }
- else{//parent
- printf("Im parent %in",getpid());
- wait(NULL);
- }
- }
- //Creating another child process from parent, this process recieves string sent from
- //childs
- pid = fork();
- if(pid < 0)
- {
- perror("fork failed");
- exit(1);
- }
- if(pid == 0){//child
- printf("The new process %i read fd pipen",getpid());
- if( read(fd[0],buffer,sizeof(buffer)) <= 0) //read pipe
- {
- perror("error read");
- exit( EXIT_FAILURE );
- }
- printf("String readed : %sn",buffer);
- }
- else{//parent
- wait(NULL);
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment