[C]Fork and waitpid


 
Thread Tools Search this Thread
Top Forums Programming [C]Fork and waitpid
# 1  
Old 12-09-2011
[C]Fork and waitpid

Hi folks, I am writing a simple program to understand how fork() and waitpid works, but it doesn't seem that is working like I wanted.

Code:
if(fork()==0){
	//el hijo
	pid1=getpid();
	printf("\nSoy el hijo %d",pid1);
}else {
	//el padre
	if (fork()==0) {
		//el hijo
		pid2=getpid();
		printf("\nSoy el hijo %d",pid2);
		 }
	else {
             .... more forks....

the father (last else)
else{
					// el padre
					// espera el hijo 1
					waitpid(pid1,status1,0);
					hijos--;
					printf("\nacaba de finalizar mi hijo con PID %d",pid1);
					//espera al hijo 2
					waitpid(pid2,status2,0);
					hijos--;
					printf("\nacaba de finalizar mi hijo con PID %d",pid2);

One of the problems I have encountered is that the printed PID by the father does not correspond to any of the childs (sometimes 0 is printed).

The other one is that the fater doesn't wait for the childs, the message "acaba de finalizar..." will pop out first than " soy el hijo...", and what I want is for the father to wait for the child to finish, and once is finished, print that the child with PID X has finished.
# 2  
Old 12-09-2011
You're not quitting in your child code, so they finish executing the child code then continue blithely on into the parent code. Since you haven't posted your complete code I can't tell what they'd be doing, but it's possible that some of your children may be fork()-ing and ending up printing like the parent should. That would explain some of the strange PID values.

Instead of using a 9-long if/else chain for 9 pid's, use a loop that can handle any number of PID's with the same code:

You should put \n at the end of the line, not the beginning, because printf only actually prints AFTER it receives a \n. printf("\nthis is a string"); will leave stuff in the buffer that might be printed twice (since fork() copies the buffer along with the rest of the process).

I'm not sure what your status1, status2, ...variables are since you didn't post that code, but since you're not using & anywhere, you're probably doing it wrong. You should give waitpid() a pointer to an integer -- not an integer, and not a bare pointer.

Code:
int main(void)
{
        int n;
        pid_t pids[10];
        for(n=0; n<10; n++)
        {
                pid[n]=fork();
                if(pid[n] == 0) // child code
                {
                        printf("My PID is %d\n", getpid());
                        exit(0); // DON'T FORGET THIS or child will keep executing!
                }
        }

        for(n=0; n<10; n++)
        {
                int s;
                waitpid(pid[n], &s, 0); // It needs a pointer TO an integer -- an address pointing to a valid 'int'.
                printf("Child %d has completed\n", pid[n]);
        }

        return(0);
}


Last edited by Corona688; 12-09-2011 at 04:44 PM..
This User Gave Thanks to Corona688 For This Post:
# 3  
Old 12-09-2011
Thanks for the insight! I will look into it tomorrow because right now I don't havem much time Smilie
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

Fork!

I understand that fork create a child but I need very simple example that make child useful.... I mean how will make the program faster anyone explain with code plz using C plz (2 Replies)
Discussion started by: fwrlfo
2 Replies

2. Programming

waitpid and grandchildren

I'm attempting to write a daemon that will start, stop, and monitor processes across a network of servers, meaning that a daemon would start on each server, attempt to connect to siblings at regular intervals (if there are unconnected siblings), and start services as remote dependencies are... (3 Replies)
Discussion started by: kshots
3 Replies

3. Programming

waiting for multiple childs - C - waitpid

Hi gurus, I would like to fork more children and then write their return values: so far I tried: #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=0, i; ... (5 Replies)
Discussion started by: wakatana
5 Replies

4. UNIX for Dummies Questions & Answers

fork()

I'm trying to run a simple test on how to use fork(), i'm able to execute the child process first then the parent, but how can I execute parent then child..? Thanks! (1 Reply)
Discussion started by: l flipboi l
1 Replies

5. Programming

Fork()

does fork() spawn only the parent process, what if fork() is looped, does it spawn the parent and the child? (4 Replies)
Discussion started by: Peevish
4 Replies

6. Programming

fork() help

Hi everybody, I wanna write a code to understand how fork works. my target -------------- -Parent creates a file(called temp) and writes into this file "1".Then it closes the file. -Then parent creates a child and wait until execution of this child ends. -Then child opens the same... (3 Replies)
Discussion started by: alexicopax
3 Replies

7. Programming

Fork ()

hi all About this code for (i = 1; i < n; i++) if ((childpid = fork()) <= 0) break; I really can't understand the output . and the way fork () return the value . how about the process Id ,the child process Id and the parent ID in this case so please answer me soon (5 Replies)
Discussion started by: iwbasts
5 Replies

8. Programming

problems with FORK() and WAITPID()

Dear All, I'm trying to write multithreading TCP Daemon which executes external program when new network connection arrives on a socket. After accept() I'm doing fork() for initiating of new child process, in which will be executed external program. After child creation I'm doing fork() again,... (3 Replies)
Discussion started by: Polkovnik
3 Replies

9. Programming

Fork or what?

Hello all. I'm developing a filetransfer application, which is supposed to work sort of like dcc, with multiple transfers etc. Now i wonder what the best way to manage the transfers is. Should i fork() for each new transfer, hogging loads of memory or use pthreads? Maybe I can use select to see... (0 Replies)
Discussion started by: crippe
0 Replies

10. Programming

fork()

#include <stdio.h> #include <string.h> #include <sys/types.h> #define MAX_COUNT 200 #define BUF_SIZE 100 void main(void) { pid_t pid; int i; char buf; fork(); pid = getpid(); for (i = 1; i <= MAX_COUNT; i++) { sprintf(buf,... (2 Replies)
Discussion started by: MKSRaja
2 Replies
Login or Register to Ask a Question