ronyal

Untitled

Nov 19th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <sys/types.h>
  3. #include <errno.h>
  4. #include <stdio.h>
  5. #include <sys/wait.h>
  6. #include <stdlib.h>
  7.  
  8. int global =0;
  9.  
  10. int main()
  11. {
  12.     pid_t child_pid;
  13.     int status;
  14.     int local = 0;
  15.     /* now create new process */
  16.     child_pid = fork();
  17.  
  18.     if (child_pid >= 0) /* fork succeeded */
  19.     {
  20.         if (child_pid == 0) /* fork() returns 0 for the child process */
  21.         {
  22.             printf("child process!\n");
  23.  
  24.             // Increment the local and global variables
  25.             local++;
  26.             global++;
  27.  
  28.             printf("child PID =  %d, parent pid = %d\n", getpid(), getppid());
  29.             printf("\n child's local = %d, child's global = %d\n",local,global);
  30.  
  31.             char *cmd[] = {"pwd",(char*)0};
  32.             return execv("/usr/bin/pwd",cmd); // call pwd command
  33.  
  34.          }
  35.          else /* parent process */
  36.          {
  37.              printf("parent process!\n");
  38.              printf("parent PID =  %d, child pid = %d\n", getpid(), child_pid);
  39.              wait(&status); /* wait for child to exit, and store child's exit status */
  40.              printf("Child exit code: %d\n", WEXITSTATUS(status));
  41.  
  42.              //The change in local and global variable in child process should not reflect here in parent process.
  43.              printf("\n Parent's local = %d, parent's  global = %d\n",local,global);
  44.  
  45.              printf("Parent says bye!\n");
  46.              exit(0);  /* parent exits */
  47.          }
  48.     }
  49.     else /* failure */
  50.     {
  51.         perror("fork");
  52.         exit(0);
  53.     }
  54. }
Add Comment
Please, Sign In to add comment