Pipe with multiple child process











up vote
0
down vote

favorite












I want to create N processes from one parent and this child processes have to read that parent write, but what i have only the first process reads correctly:



#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv){


pid_t pid;

int fd[2];
char buff[50];

char str = "Hello";

if(pipe(fd) == -1){
fprintf(stderr, "pipe Failed");
return 1;
}

for(int num_process = 0; num_process < 3; num_process++){
pid = fork();
if(pid < 0){
perror("Error");
exit(1);
}

if(pid == 0){ //child code
printf("Child %i (pid= %i)n", num_process, getpid());


close(fd[1]);
read(fd[0], buff, sizeof(buff)); //read from pipe
printf("Read child = %sn", buff);
close(fd[0]);
exit(0);
}

else{//parent
printf("Im parent %in",getpid());
close(fd[0]);
write(fd[1], str,strlen(str)+1);
printf("Parent send %sn", str);
close(fd[1]);
for(int num_process = 0; num_process < 3; num_process++){
wait(NULL);
}
}
}

return 0;
}


output:



Im parent 5863
Parent send Hello
Child 0 (pid= 5864)
Read child = Hello
Im parent 5863
Parent send Hello
Child 1 (pid= 5865)
Read child =
Im parent 5863
Parent send Hello
Child 2 (pid= 5866)
Read child =









share|improve this question













migrated from unix.stackexchange.com 2 days ago


This question came from our site for users of Linux, FreeBSD and other Un*x-like operating systems.















  • OT: regarding: int main(int argc, char *argv){ when the parameters to main() are not being used, then use the signature: int main( void )
    – user3629249
    Dec 6 at 0:00










  • OT: for ease of readability and understanding: 1) consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces.
    – user3629249
    Dec 6 at 0:03










  • OT: the posted code contains some 'magic' number. I.E. 3. 'magic' numbers make the code more difficult to understand, debug, etc. Suggest using an enum statement or a #define statement to give that 'magic' number a meaningful name, then use that meanindful name throughout the code.
    – user3629249
    Dec 6 at 0:17










  • regarding: if(pid < 0){ perror("Error"); exit(1); This will have the parent exiting while one or more children processes are still running. (a handy to create zombie processes.) Suggest inserting a wait() or waitpid() for each child process before calling exit()
    – user3629249
    Dec 6 at 0:19










  • Regarding: for(int num_process = 0; num_process < 3; num_process++) { wait(NULL); } This loop is inside the loop that is creating the child processes. It should be after all the children are created
    – user3629249
    Dec 6 at 0:24















up vote
0
down vote

favorite












I want to create N processes from one parent and this child processes have to read that parent write, but what i have only the first process reads correctly:



#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv){


pid_t pid;

int fd[2];
char buff[50];

char str = "Hello";

if(pipe(fd) == -1){
fprintf(stderr, "pipe Failed");
return 1;
}

for(int num_process = 0; num_process < 3; num_process++){
pid = fork();
if(pid < 0){
perror("Error");
exit(1);
}

if(pid == 0){ //child code
printf("Child %i (pid= %i)n", num_process, getpid());


close(fd[1]);
read(fd[0], buff, sizeof(buff)); //read from pipe
printf("Read child = %sn", buff);
close(fd[0]);
exit(0);
}

else{//parent
printf("Im parent %in",getpid());
close(fd[0]);
write(fd[1], str,strlen(str)+1);
printf("Parent send %sn", str);
close(fd[1]);
for(int num_process = 0; num_process < 3; num_process++){
wait(NULL);
}
}
}

return 0;
}


output:



Im parent 5863
Parent send Hello
Child 0 (pid= 5864)
Read child = Hello
Im parent 5863
Parent send Hello
Child 1 (pid= 5865)
Read child =
Im parent 5863
Parent send Hello
Child 2 (pid= 5866)
Read child =









share|improve this question













migrated from unix.stackexchange.com 2 days ago


This question came from our site for users of Linux, FreeBSD and other Un*x-like operating systems.















  • OT: regarding: int main(int argc, char *argv){ when the parameters to main() are not being used, then use the signature: int main( void )
    – user3629249
    Dec 6 at 0:00










  • OT: for ease of readability and understanding: 1) consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces.
    – user3629249
    Dec 6 at 0:03










  • OT: the posted code contains some 'magic' number. I.E. 3. 'magic' numbers make the code more difficult to understand, debug, etc. Suggest using an enum statement or a #define statement to give that 'magic' number a meaningful name, then use that meanindful name throughout the code.
    – user3629249
    Dec 6 at 0:17










  • regarding: if(pid < 0){ perror("Error"); exit(1); This will have the parent exiting while one or more children processes are still running. (a handy to create zombie processes.) Suggest inserting a wait() or waitpid() for each child process before calling exit()
    – user3629249
    Dec 6 at 0:19










  • Regarding: for(int num_process = 0; num_process < 3; num_process++) { wait(NULL); } This loop is inside the loop that is creating the child processes. It should be after all the children are created
    – user3629249
    Dec 6 at 0:24













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I want to create N processes from one parent and this child processes have to read that parent write, but what i have only the first process reads correctly:



#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv){


pid_t pid;

int fd[2];
char buff[50];

char str = "Hello";

if(pipe(fd) == -1){
fprintf(stderr, "pipe Failed");
return 1;
}

for(int num_process = 0; num_process < 3; num_process++){
pid = fork();
if(pid < 0){
perror("Error");
exit(1);
}

if(pid == 0){ //child code
printf("Child %i (pid= %i)n", num_process, getpid());


close(fd[1]);
read(fd[0], buff, sizeof(buff)); //read from pipe
printf("Read child = %sn", buff);
close(fd[0]);
exit(0);
}

else{//parent
printf("Im parent %in",getpid());
close(fd[0]);
write(fd[1], str,strlen(str)+1);
printf("Parent send %sn", str);
close(fd[1]);
for(int num_process = 0; num_process < 3; num_process++){
wait(NULL);
}
}
}

return 0;
}


output:



Im parent 5863
Parent send Hello
Child 0 (pid= 5864)
Read child = Hello
Im parent 5863
Parent send Hello
Child 1 (pid= 5865)
Read child =
Im parent 5863
Parent send Hello
Child 2 (pid= 5866)
Read child =









share|improve this question













I want to create N processes from one parent and this child processes have to read that parent write, but what i have only the first process reads correctly:



#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv){


pid_t pid;

int fd[2];
char buff[50];

char str = "Hello";

if(pipe(fd) == -1){
fprintf(stderr, "pipe Failed");
return 1;
}

for(int num_process = 0; num_process < 3; num_process++){
pid = fork();
if(pid < 0){
perror("Error");
exit(1);
}

if(pid == 0){ //child code
printf("Child %i (pid= %i)n", num_process, getpid());


close(fd[1]);
read(fd[0], buff, sizeof(buff)); //read from pipe
printf("Read child = %sn", buff);
close(fd[0]);
exit(0);
}

else{//parent
printf("Im parent %in",getpid());
close(fd[0]);
write(fd[1], str,strlen(str)+1);
printf("Parent send %sn", str);
close(fd[1]);
for(int num_process = 0; num_process < 3; num_process++){
wait(NULL);
}
}
}

return 0;
}


output:



Im parent 5863
Parent send Hello
Child 0 (pid= 5864)
Read child = Hello
Im parent 5863
Parent send Hello
Child 1 (pid= 5865)
Read child =
Im parent 5863
Parent send Hello
Child 2 (pid= 5866)
Read child =






linux c






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 5 at 23:34









Julio Bermel

102




102




migrated from unix.stackexchange.com 2 days ago


This question came from our site for users of Linux, FreeBSD and other Un*x-like operating systems.






migrated from unix.stackexchange.com 2 days ago


This question came from our site for users of Linux, FreeBSD and other Un*x-like operating systems.














  • OT: regarding: int main(int argc, char *argv){ when the parameters to main() are not being used, then use the signature: int main( void )
    – user3629249
    Dec 6 at 0:00










  • OT: for ease of readability and understanding: 1) consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces.
    – user3629249
    Dec 6 at 0:03










  • OT: the posted code contains some 'magic' number. I.E. 3. 'magic' numbers make the code more difficult to understand, debug, etc. Suggest using an enum statement or a #define statement to give that 'magic' number a meaningful name, then use that meanindful name throughout the code.
    – user3629249
    Dec 6 at 0:17










  • regarding: if(pid < 0){ perror("Error"); exit(1); This will have the parent exiting while one or more children processes are still running. (a handy to create zombie processes.) Suggest inserting a wait() or waitpid() for each child process before calling exit()
    – user3629249
    Dec 6 at 0:19










  • Regarding: for(int num_process = 0; num_process < 3; num_process++) { wait(NULL); } This loop is inside the loop that is creating the child processes. It should be after all the children are created
    – user3629249
    Dec 6 at 0:24


















  • OT: regarding: int main(int argc, char *argv){ when the parameters to main() are not being used, then use the signature: int main( void )
    – user3629249
    Dec 6 at 0:00










  • OT: for ease of readability and understanding: 1) consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces.
    – user3629249
    Dec 6 at 0:03










  • OT: the posted code contains some 'magic' number. I.E. 3. 'magic' numbers make the code more difficult to understand, debug, etc. Suggest using an enum statement or a #define statement to give that 'magic' number a meaningful name, then use that meanindful name throughout the code.
    – user3629249
    Dec 6 at 0:17










  • regarding: if(pid < 0){ perror("Error"); exit(1); This will have the parent exiting while one or more children processes are still running. (a handy to create zombie processes.) Suggest inserting a wait() or waitpid() for each child process before calling exit()
    – user3629249
    Dec 6 at 0:19










  • Regarding: for(int num_process = 0; num_process < 3; num_process++) { wait(NULL); } This loop is inside the loop that is creating the child processes. It should be after all the children are created
    – user3629249
    Dec 6 at 0:24
















OT: regarding: int main(int argc, char *argv){ when the parameters to main() are not being used, then use the signature: int main( void )
– user3629249
Dec 6 at 0:00




OT: regarding: int main(int argc, char *argv){ when the parameters to main() are not being used, then use the signature: int main( void )
– user3629249
Dec 6 at 0:00












OT: for ease of readability and understanding: 1) consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces.
– user3629249
Dec 6 at 0:03




OT: for ease of readability and understanding: 1) consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces.
– user3629249
Dec 6 at 0:03












OT: the posted code contains some 'magic' number. I.E. 3. 'magic' numbers make the code more difficult to understand, debug, etc. Suggest using an enum statement or a #define statement to give that 'magic' number a meaningful name, then use that meanindful name throughout the code.
– user3629249
Dec 6 at 0:17




OT: the posted code contains some 'magic' number. I.E. 3. 'magic' numbers make the code more difficult to understand, debug, etc. Suggest using an enum statement or a #define statement to give that 'magic' number a meaningful name, then use that meanindful name throughout the code.
– user3629249
Dec 6 at 0:17












regarding: if(pid < 0){ perror("Error"); exit(1); This will have the parent exiting while one or more children processes are still running. (a handy to create zombie processes.) Suggest inserting a wait() or waitpid() for each child process before calling exit()
– user3629249
Dec 6 at 0:19




regarding: if(pid < 0){ perror("Error"); exit(1); This will have the parent exiting while one or more children processes are still running. (a handy to create zombie processes.) Suggest inserting a wait() or waitpid() for each child process before calling exit()
– user3629249
Dec 6 at 0:19












Regarding: for(int num_process = 0; num_process < 3; num_process++) { wait(NULL); } This loop is inside the loop that is creating the child processes. It should be after all the children are created
– user3629249
Dec 6 at 0:24




Regarding: for(int num_process = 0; num_process < 3; num_process++) { wait(NULL); } This loop is inside the loop that is creating the child processes. It should be after all the children are created
– user3629249
Dec 6 at 0:24












2 Answers
2






active

oldest

votes

















up vote
1
down vote



accepted











read(fd[0], buff, sizeof(buff)); //read from pipe
printf("Read child = %sn", buff);



If you did check the return value of read (as you always should) you would've seen that the 2nd and 3rd time it returns -1 and sets errno to EBADF. That's because you've already closed the read end of the pipe in the first iteration of the loop, in the "parent" part, here:




   printf("Im parent %in",getpid());
close(fd[0]);



The same thing with the write following it:




   write(fd[1], str,strlen(str)+1);
printf("Parent send %sn", str);
close(fd[1]);



fd[1] will be closed in the 1st iteration of the loop, and the write will fail with EBADF the 2nd and 3rd time.






share|improve this answer





















  • So, what's the purpose of close pipes?
    – Julio Bermel
    Dec 6 at 0:12






  • 1




    You should only do the close(fd[1]) in the child.
    – mosvy
    Dec 6 at 0:16


















up vote
0
down vote













the following proposed code:




  1. handles each child separately

  2. performs the desired functionality

  3. incorporates the comments to the OPs question

  4. caveat: the closing of the pipe ends is somewhat careless in the proposed code


and now the proposed code:



#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>

#define MAX_CHILDREN 3

int main( void )
{
pid_t pid;

int fd[2];


char str = "Hello";

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
char buff[50];
printf("Child %i (pid= %i)n", num_process, getpid());
close(fd[1]);

if ( read( fd[0], buff, sizeof(buff)) <= 0) //read from pipe
{
perror( "read failed" );
exit( EXIT_FAILURE );
}

printf("Read child = %sn", buff);
exit(0);
}

else{//parent
printf("Im parent %in",getpid());
close(fd[0]);
write(fd[1], str,strlen(str)+1);
printf("Parent send %sn", str);
wait(NULL);
}
}

return 0;
}


A typical run of the code results in:



Im parent 26451
Parent send Hello
Child 0 (pid= 26452)
Read child = Hello
Im parent 26451
Parent send Hello
Child 1 (pid= 26453)
Read child = Hello
Im parent 26451
Parent send Hello
Child 2 (pid= 26454)
Read child = Hello





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53646103%2fpipe-with-multiple-child-process%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted











    read(fd[0], buff, sizeof(buff)); //read from pipe
    printf("Read child = %sn", buff);



    If you did check the return value of read (as you always should) you would've seen that the 2nd and 3rd time it returns -1 and sets errno to EBADF. That's because you've already closed the read end of the pipe in the first iteration of the loop, in the "parent" part, here:




       printf("Im parent %in",getpid());
    close(fd[0]);



    The same thing with the write following it:




       write(fd[1], str,strlen(str)+1);
    printf("Parent send %sn", str);
    close(fd[1]);



    fd[1] will be closed in the 1st iteration of the loop, and the write will fail with EBADF the 2nd and 3rd time.






    share|improve this answer





















    • So, what's the purpose of close pipes?
      – Julio Bermel
      Dec 6 at 0:12






    • 1




      You should only do the close(fd[1]) in the child.
      – mosvy
      Dec 6 at 0:16















    up vote
    1
    down vote



    accepted











    read(fd[0], buff, sizeof(buff)); //read from pipe
    printf("Read child = %sn", buff);



    If you did check the return value of read (as you always should) you would've seen that the 2nd and 3rd time it returns -1 and sets errno to EBADF. That's because you've already closed the read end of the pipe in the first iteration of the loop, in the "parent" part, here:




       printf("Im parent %in",getpid());
    close(fd[0]);



    The same thing with the write following it:




       write(fd[1], str,strlen(str)+1);
    printf("Parent send %sn", str);
    close(fd[1]);



    fd[1] will be closed in the 1st iteration of the loop, and the write will fail with EBADF the 2nd and 3rd time.






    share|improve this answer





















    • So, what's the purpose of close pipes?
      – Julio Bermel
      Dec 6 at 0:12






    • 1




      You should only do the close(fd[1]) in the child.
      – mosvy
      Dec 6 at 0:16













    up vote
    1
    down vote



    accepted







    up vote
    1
    down vote



    accepted







    read(fd[0], buff, sizeof(buff)); //read from pipe
    printf("Read child = %sn", buff);



    If you did check the return value of read (as you always should) you would've seen that the 2nd and 3rd time it returns -1 and sets errno to EBADF. That's because you've already closed the read end of the pipe in the first iteration of the loop, in the "parent" part, here:




       printf("Im parent %in",getpid());
    close(fd[0]);



    The same thing with the write following it:




       write(fd[1], str,strlen(str)+1);
    printf("Parent send %sn", str);
    close(fd[1]);



    fd[1] will be closed in the 1st iteration of the loop, and the write will fail with EBADF the 2nd and 3rd time.






    share|improve this answer













    read(fd[0], buff, sizeof(buff)); //read from pipe
    printf("Read child = %sn", buff);



    If you did check the return value of read (as you always should) you would've seen that the 2nd and 3rd time it returns -1 and sets errno to EBADF. That's because you've already closed the read end of the pipe in the first iteration of the loop, in the "parent" part, here:




       printf("Im parent %in",getpid());
    close(fd[0]);



    The same thing with the write following it:




       write(fd[1], str,strlen(str)+1);
    printf("Parent send %sn", str);
    close(fd[1]);



    fd[1] will be closed in the 1st iteration of the loop, and the write will fail with EBADF the 2nd and 3rd time.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Dec 6 at 0:02









    mosvy

    53914




    53914












    • So, what's the purpose of close pipes?
      – Julio Bermel
      Dec 6 at 0:12






    • 1




      You should only do the close(fd[1]) in the child.
      – mosvy
      Dec 6 at 0:16


















    • So, what's the purpose of close pipes?
      – Julio Bermel
      Dec 6 at 0:12






    • 1




      You should only do the close(fd[1]) in the child.
      – mosvy
      Dec 6 at 0:16
















    So, what's the purpose of close pipes?
    – Julio Bermel
    Dec 6 at 0:12




    So, what's the purpose of close pipes?
    – Julio Bermel
    Dec 6 at 0:12




    1




    1




    You should only do the close(fd[1]) in the child.
    – mosvy
    Dec 6 at 0:16




    You should only do the close(fd[1]) in the child.
    – mosvy
    Dec 6 at 0:16












    up vote
    0
    down vote













    the following proposed code:




    1. handles each child separately

    2. performs the desired functionality

    3. incorporates the comments to the OPs question

    4. caveat: the closing of the pipe ends is somewhat careless in the proposed code


    and now the proposed code:



    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/wait.h>

    #define MAX_CHILDREN 3

    int main( void )
    {
    pid_t pid;

    int fd[2];


    char str = "Hello";

    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
    char buff[50];
    printf("Child %i (pid= %i)n", num_process, getpid());
    close(fd[1]);

    if ( read( fd[0], buff, sizeof(buff)) <= 0) //read from pipe
    {
    perror( "read failed" );
    exit( EXIT_FAILURE );
    }

    printf("Read child = %sn", buff);
    exit(0);
    }

    else{//parent
    printf("Im parent %in",getpid());
    close(fd[0]);
    write(fd[1], str,strlen(str)+1);
    printf("Parent send %sn", str);
    wait(NULL);
    }
    }

    return 0;
    }


    A typical run of the code results in:



    Im parent 26451
    Parent send Hello
    Child 0 (pid= 26452)
    Read child = Hello
    Im parent 26451
    Parent send Hello
    Child 1 (pid= 26453)
    Read child = Hello
    Im parent 26451
    Parent send Hello
    Child 2 (pid= 26454)
    Read child = Hello





    share|improve this answer

























      up vote
      0
      down vote













      the following proposed code:




      1. handles each child separately

      2. performs the desired functionality

      3. incorporates the comments to the OPs question

      4. caveat: the closing of the pipe ends is somewhat careless in the proposed code


      and now the proposed code:



      #include <stdio.h>
      #include <unistd.h>
      #include <sys/types.h>
      #include <stdlib.h>
      #include <string.h>
      #include <sys/wait.h>

      #define MAX_CHILDREN 3

      int main( void )
      {
      pid_t pid;

      int fd[2];


      char str = "Hello";

      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
      char buff[50];
      printf("Child %i (pid= %i)n", num_process, getpid());
      close(fd[1]);

      if ( read( fd[0], buff, sizeof(buff)) <= 0) //read from pipe
      {
      perror( "read failed" );
      exit( EXIT_FAILURE );
      }

      printf("Read child = %sn", buff);
      exit(0);
      }

      else{//parent
      printf("Im parent %in",getpid());
      close(fd[0]);
      write(fd[1], str,strlen(str)+1);
      printf("Parent send %sn", str);
      wait(NULL);
      }
      }

      return 0;
      }


      A typical run of the code results in:



      Im parent 26451
      Parent send Hello
      Child 0 (pid= 26452)
      Read child = Hello
      Im parent 26451
      Parent send Hello
      Child 1 (pid= 26453)
      Read child = Hello
      Im parent 26451
      Parent send Hello
      Child 2 (pid= 26454)
      Read child = Hello





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        the following proposed code:




        1. handles each child separately

        2. performs the desired functionality

        3. incorporates the comments to the OPs question

        4. caveat: the closing of the pipe ends is somewhat careless in the proposed code


        and now the proposed code:



        #include <stdio.h>
        #include <unistd.h>
        #include <sys/types.h>
        #include <stdlib.h>
        #include <string.h>
        #include <sys/wait.h>

        #define MAX_CHILDREN 3

        int main( void )
        {
        pid_t pid;

        int fd[2];


        char str = "Hello";

        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
        char buff[50];
        printf("Child %i (pid= %i)n", num_process, getpid());
        close(fd[1]);

        if ( read( fd[0], buff, sizeof(buff)) <= 0) //read from pipe
        {
        perror( "read failed" );
        exit( EXIT_FAILURE );
        }

        printf("Read child = %sn", buff);
        exit(0);
        }

        else{//parent
        printf("Im parent %in",getpid());
        close(fd[0]);
        write(fd[1], str,strlen(str)+1);
        printf("Parent send %sn", str);
        wait(NULL);
        }
        }

        return 0;
        }


        A typical run of the code results in:



        Im parent 26451
        Parent send Hello
        Child 0 (pid= 26452)
        Read child = Hello
        Im parent 26451
        Parent send Hello
        Child 1 (pid= 26453)
        Read child = Hello
        Im parent 26451
        Parent send Hello
        Child 2 (pid= 26454)
        Read child = Hello





        share|improve this answer












        the following proposed code:




        1. handles each child separately

        2. performs the desired functionality

        3. incorporates the comments to the OPs question

        4. caveat: the closing of the pipe ends is somewhat careless in the proposed code


        and now the proposed code:



        #include <stdio.h>
        #include <unistd.h>
        #include <sys/types.h>
        #include <stdlib.h>
        #include <string.h>
        #include <sys/wait.h>

        #define MAX_CHILDREN 3

        int main( void )
        {
        pid_t pid;

        int fd[2];


        char str = "Hello";

        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
        char buff[50];
        printf("Child %i (pid= %i)n", num_process, getpid());
        close(fd[1]);

        if ( read( fd[0], buff, sizeof(buff)) <= 0) //read from pipe
        {
        perror( "read failed" );
        exit( EXIT_FAILURE );
        }

        printf("Read child = %sn", buff);
        exit(0);
        }

        else{//parent
        printf("Im parent %in",getpid());
        close(fd[0]);
        write(fd[1], str,strlen(str)+1);
        printf("Parent send %sn", str);
        wait(NULL);
        }
        }

        return 0;
        }


        A typical run of the code results in:



        Im parent 26451
        Parent send Hello
        Child 0 (pid= 26452)
        Read child = Hello
        Im parent 26451
        Parent send Hello
        Child 1 (pid= 26453)
        Read child = Hello
        Im parent 26451
        Parent send Hello
        Child 2 (pid= 26454)
        Read child = Hello






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 6 at 0:56









        user3629249

        10.8k1914




        10.8k1914






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53646103%2fpipe-with-multiple-child-process%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Accessing regular linux commands in Huawei's Dopra Linux

            Can't connect RFCOMM socket: Host is down

            Kernel panic - not syncing: Fatal Exception in Interrupt