Why Isn't My Linux Child Process Program Working?

  • Thread starter Thread starter khdani
  • Start date Start date
  • Tags Tags
    Linux Program
AI Thread Summary
The discussion revolves around a programming issue related to creating and managing child processes in C. The user is attempting to create a specified number of child processes sequentially and then destroy them in reverse order. The provided code uses `fork()` to create child processes and `wait()` to manage their termination. However, the user encounters problems with the expected behavior of the program. The key issue identified is that the `wait()` function is called inside the loop, which causes the parent process to wait for each child to terminate before creating the next one. This leads to incorrect sequencing of child creation and destruction. The solution involves restructuring the code to allow for the creation of all child processes before waiting for their termination, thereby achieving the desired functionality.
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
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top