Why Isn't My Linux Child Process Program Working?

  • Thread starter Thread starter khdani
  • Start date Start date
  • Tags Tags
    Linux Program
Click For Summary
SUMMARY

The discussion centers on a C program designed to create child processes sequentially and terminate them in reverse order. The user input for the number of child processes is captured, but the program fails to execute as intended. The issue arises from the placement of the wait function, which causes the parent process to wait for the child process to terminate before creating the next child. The solution involves adjusting the logic to ensure that the parent process continues to create child processes without waiting prematurely.

PREREQUISITES
  • Understanding of C programming language
  • Familiarity with process management in Unix/Linux
  • Knowledge of the fork() and wait() system calls
  • Basic concepts of process IDs (PIDs) and parent-child relationships in operating systems
NEXT STEPS
  • Review the use of fork() and wait() in C programming
  • Learn about process synchronization techniques in Unix/Linux
  • Explore advanced process management using signals in C
  • Investigate the use of exec() family functions for executing new programs in child processes
USEFUL FOR

Software developers, particularly those working with C programming and Unix/Linux systems, as well as students learning about process management and inter-process communication.

khdani
Messages
53
Reaction score
0
Hello,
I try to make a program which gets the number of desired childs from user, then creates them sequentially and destroys them in reverse order.
I just don't understand why it doesn't work correctly :(

Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc, char** argv) {
        int pid, status,n_sons,current_son=0;
        printf("Enter number of sons:");
        scanf("%d",&n_sons);

        do {
                pid=fork();
                if(pid !=0 ) {
                        printf("Created Son, with PID:%d and PPID:%d\n",pid,getppid());
                        wait(&status);
                        printf("Son with PID:%d, terminated with status:%d\n",pid,status);
                        break;
                }
                else {
                       current_son++;
                }
        }while(current_son < n_sons);

        return 0;
}
 
Technology news on Phys.org
found the problem
 

Similar threads

Replies
8
Views
4K
Replies
14
Views
4K
Replies
7
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 6 ·
Replies
6
Views
6K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K