Created
          July 25, 2018 08:20 
        
      - 
      
- 
        Save NorbertFenk/66854392234dd1f160c3545f20f8c286 to your computer and use it in GitHub Desktop. 
    Short program to show forking in C++ and how to create zombie process. 
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #include <iostream> | |
| #include <unistd.h> | |
| int main() | |
| { | |
| std::cout << "------ program started ------" << std::endl; | |
| int counter = 0; | |
| pid_t pid = fork(); | |
| /* | |
| * fork() returns -1 if it fails, | |
| * and if it succeeds, it returns the forked child's pid in the parent, | |
| * and 0 in the child. So if (fork() != 0) tests whether it's the parent process. | |
| */ | |
| if (pid == 0) { | |
| // child process | |
| for (int i = 0; i < 5; ++i) { | |
| //sleep(5); | |
| counter += 1; | |
| std::cout << "child process: counter = " << counter << std::endl; | |
| } | |
| /* | |
| * to create zombie process uncomment this line and the sleep(30) in the parent branch -> | |
| * you can chack it with ps aux | grep <process name> -> Z will indicate it is a zombie | |
| */ | |
| // exit(0); | |
| } else if (pid > 0) { | |
| //sleep(30); | |
| // parent process | |
| for(int i = 0; i < 5; ++i) { | |
| sleep(5); | |
| counter += 5; | |
| std::cout << "parent process: counter = " << counter << std::endl; | |
| } | |
| } else { | |
| // fork failed | |
| std::cout << "fork() failed" << std::endl; | |
| return 1; | |
| } | |
| std::cout << "------ end of program pid = " << pid << "------" << std::endl; | |
| return 0; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment