c - Parent process does not reap child return variable -


this class trying understand why variable nchars not being set when child process returns. have read waitpid() reaps child process when try print nchars still shows 0 when childs' nchars number of commandline characters

int main(int argc, char **argv) {     // set pipe   int      fd[2], status;   pid_t    childpid;    pipe(fd);     // call fork()   if((childpid = fork()) == -1){     perror("pipe");     return -1;   }   if (childpid == 0) {         // -- running in child process --         int     nchars = 0;         char    ch;          close(fd[1]);         // receive characters parent process via pipe         // 1 @ time, , count them.          while(read(fd[0], &ch, 1) == 1)nchars++;          // return number of characters counted parent process.         printf("child returns %d\n", nchars);         close(fd[0]);          return nchars;     }     else {         // -- running in parent process --         int     nchars = 0;         close(fd[0]);          printf("cs201 - assignment 3 - \n");          // send characters command line arguments starting         // argv[1] 1 @ time through pipe child process.          for(int i=1; < argc; i++)             write(fd[1], argv[i], strlen(argv[i]));           // wait child process return. reap child process.         // receive number of characters counted via value         // returned when child process reaped.          waitpid(childpid, &status, wnohang);         printf("child counted %d characters\n", nchars);         close(fd[1]);   return 0;   } 

parent , child don't share memory, have different variables nchars. child copy of parent, when change variables in copy doesn't changed in original. if need have 1 variable visible 2 execution flows use threads.

you're returning nchars child process exit code, it'll in status variable. try:

waitpid(childpid, &status, 0); // removed wnohang because parent won't wait child exit printf("child counted %d characters\n", status); 

but better use come ipc mechanism pipes or sockets transfer data between child , parent, because exit codes program exit status, exit code 0 means okay, , other exit codes mean gone wrong, exit code not transferring arbitrary data


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -