parent called more times - fork - C language


 
Thread Tools Search this Thread
Top Forums Programming parent called more times - fork - C language
# 1  
Old 02-22-2011
parent called more times - fork - C language

Hi gurus can you explain following lines of code ?

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

int main(void)
{
    pid_t pid;
    int rv;

    switch(pid = fork()) {
    case -1:
        perror("fork");  /* something went wrong */
        exit(1);         /* parent exits */

    case 0:
        printf(" CHILD: This is the child process!\n");
        printf(" CHILD: My PID is %d\n", getpid());
        printf(" CHILD: My parent's PID is %d\n", getppid());
    printf(" CHILD: I am sleeping for 15 seconds\n");
        sleep(15);           // exits as a second
    printf(" CHILD: Sleeping is over\n");
    


    default:
        printf("PARENT: This is the parent process!\n");
        printf("PARENT: My PID is %d\n", getpid());
        printf("PARENT: My child's PID is %d\n", pid);
    printf("PARENT: I am sleeping for 10 seconds\n");
        sleep(10);             // exits first
    printf("PARENT: Sleeping is over\n");
    }

    return 0;
}

As far as I know:
- if fork() function is called - code is executing in child and parent section (if fork() did not exits with -1 of course)
- after calling fork() function all code after fork() is executed sequentially (but due to sheduller is unable to predict if will be executed parent or child part of code)
- if parent code exits before child code (without waiting or hadnling signal), childs new parent will be init proces (PPID 1)

I get the following output


Code:
bash-3.2$ ./a2.out
PARENT: This is the parent process!
 CHILD: This is the child process!
PARENT: My PID is 15852
PARENT: My child's PID is 15853
PARENT: I am sleeping for 10 seconds
 CHILD: My PID is 15853
 CHILD: My parent's PID is 15852
 CHILD: I am sleeping for 15 seconds
PARENT: Sleeping is over
bash-3.2$  CHILD: Sleeping is over
PARENT: This is the parent process!
PARENT: My PID is 15853
PARENT: My child's PID is 0
PARENT: I am sleeping for 10 seconds
PARENT: Sleeping is over

So my question is:
- why is not child mark as defunct when parent exits first ? (I tried ps -elf | grep defunct during execution of code)
- Why is parent code executed second time (but now with the pid of child ?)

Thanks a lot
# 2  
Old 02-22-2011
First, replace all printf(...) with fprintf(stderr, ...). There's no way to tell what's really printing what when right now, because there may be buffers getting flushed after you forked.

---------- Post updated at 07:43 PM ---------- Previous update was at 07:41 PM ----------

Also, you never put a break; at the end of the child section so it keeps running down through the parent section. imagine a case to be a goto: It just magically jumps to that location and keeps going until you tell it to stop with a break;
# 3  
Old 02-23-2011
If you run this piece of code you will have different outcomes. Sometimes the father code can be executed before the son's code and vice-versa, because the operating systems stagger them. And a process has some limited time for accessing the CPU which is called Time Slice, when a process time slice rans out the OS switch to another process that is waiting to be executed.

All you need to know It is how the fork () syscall works and this lit.le concept.

I hope I hellped-
# 4  
Old 02-25-2011
Thanks both - now it is clear why I had run 2 times parent (because of missing break) and also did not know that child can started before son. But anyway if I add break why I did not get the son process as defunct or zombie ?
# 5  
Old 02-25-2011
Once the parent processes quit, the child processes change ownership to process 1, 'init', which reaps them for you. Zombies happen when the parent is still alive but not reaping its children.
# 6  
Old 02-26-2011
Quote:
Originally Posted by Corona688
Zombies happen when the parent is still alive but not reaping its children.
Is it possible to code application this way ? - I assumed if I did not catch SIGCHLD in parent with wait() function this happens

Last edited by wakatana; 02-26-2011 at 06:23 PM..
# 7  
Old 02-26-2011
Quote:
Originally Posted by wakatana
Is it possible to code application this way ?
Put a sleep(60) before the parent begins wait()ing for children and look for the children in the process table(ps). If they've quit, they should be zombies until the parent wait()'s for them.
Quote:
I assumed if I did not catch SIGCHLD in parent with wait() function this happens
Sort of. wait()ing for a process removes its zombie from the process table, but if the parent quits while its children are still zombies, they get owned by init, which will wait() for them itself. So zombies mostly happen while the parent is still alive.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

One parent, multiple children pipe with fork()

The task I have to do is something along the lines "I receive some input and based on the first character I send it through pipe to one of the children to print". The scheme it is based on is 1->2; 1->3; 1->4; 2 will print all the input that starts with a letter, 3 will print all the input that... (2 Replies)
Discussion started by: Ildiko
2 Replies

2. UNIX for Dummies Questions & Answers

shell program- how many times a function is called

We have a program source C and is required to indicate how many times each function is called from the C program. also print the line number where there is a call. I've tried something like this: #!/bin/sh for i in $*;do if ! then echo $i is not a C file. else echo $i... (0 Replies)
Discussion started by: oana06
0 Replies

3. UNIX for Advanced & Expert Users

System call failed with 127 .. after 500 times when called in loop

Hi Experts, I have a code like this. ===== #include.... int main() { int count = 0; while(1){ printf("\n Interation number is: %d \n ",count); rv = system(" test.sh > log.txt " ); if (-1 == rv) { printf("Could not generate static log: error... (12 Replies)
Discussion started by: binnyjeshan
12 Replies

4. Programming

fork(), parent and child processes???

Hi friends, I have a small question regarding unix system call fork, I hope you will solve my problem. Here is the small program $ cat fork1.c #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main() { int pid; int x = 0; x = x + 1; pid = fork(); if(pid < 0) {... (2 Replies)
Discussion started by: gabam
2 Replies

5. Programming

Problem with implementing the times() function in C (struct tms times return zero/negative values)

Hello, i'm trying to implement the times() function and i'm programming in C. I'm using the "struct tms" structure which consists of the fields: The tms_utime structure member is the CPU time charged for the execution of user instructions of the calling process. The tms_stime structure... (1 Reply)
Discussion started by: g_p
1 Replies

6. Programming

Timed action after fork() in parent process

Assume you have such a piece of (more or less pseudo-)code: if(fork() == 0) {// childprocess chmod(someProgram, 00777); exec(someProgram); } else { // assume it never fails and this is the parent chmod(someProgram, 00000); // should be executed as soon as possible after the... (5 Replies)
Discussion started by: disaster
5 Replies

7. UNIX for Advanced & Expert Users

Fork() 1 Parent 3 Children

Hi, as I understand fork(), it makes a copy of the parent which becomes a child. But is there anyway to make three children for that one parent. So in other words, if I look up the getppid() of the children, I want them to have the same value?? Thanks in advance to any help! (1 Reply)
Discussion started by: MS_CC
1 Replies

8. Shell Programming and Scripting

full path of a file situated either in parent's dir. or parent's parent dir. so on...

hi experts(novice people can stay away as it is no child's game), i am developing a script which works like recycle bin of windows. the problem i am facing is that when ever i am trying to delete a file which is situated in parent directory or parent's parent directory i am unable to... (1 Reply)
Discussion started by: yahoo!
1 Replies

9. Programming

Problems with child comunicating with parent on fork()

Hello, I'm trying to implement a version of a bucketSort (kinda) server/client, but I'm having a VERY hard time on making the server behave correctly, when talking to the children, after it forks. The server is kinda big (300+ lines), so I won't post it here, but here's what I'm doing. 1)create a... (8 Replies)
Discussion started by: Zarnick
8 Replies

10. Programming

display in a child process a command called in the parent one

Hi , Could you tell me if I am right 1. Using fork(), pipe(), execlp() and dup() (see man 2 dup), write a C program executing the command ps -j in a parent process, displaying the result in a child process. #include <unistd.h> #include <errno.h> #include <stdio.h> #include <unistd.h>... (7 Replies)
Discussion started by: remid1985
7 Replies
Login or Register to Ask a Question