Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Bash / Shell Scripting (http://www.programmingforums.org/forum26.html)
-   -   Hi, I Need Help With The Fork() Command (http://www.programmingforums.org/showthread.php?t=804)

Tazz13 Oct 10th, 2004 6:59 PM

Hi,

I need some help with using the fork() command. What I need to do is have the program create 3 child processes using fork() then each of the 3 child processes create 1 process each using fork(). Then I need the proces ID's of each process to be printed.

I have gotten the first part where I create 3 child processes, now I don't know where to insert another fork() such that each of the 3 child processes creates 1 child process of its own.

I am using the bash shell and using the "Pico" text editor to write this C Program. I am using the 'gcc' compile command to compile the program.

Here is the code I have so far:

:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void main()
{
 *int i;
 *int n;
 *pid_t childpid;

 *for(i = 1; i < 4; ++i)
 *{
 * * if((childpid = fork()) <= 0)
 * * {
 * * * *break;
 * * }
 *}

 *fprintf(stderr, "This process %ld with parent %ld\n", (long)getpid(), (long)getppid());
}


Sebeq Oct 10th, 2004 8:40 PM

Quote:


#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void main()
{
int i;
int n;
pid_t childpid;

for(i = 1; i < 4; ++i)
{
if((childpid = fork()) <= 0)
{
break;
}
}

fprintf(stderr, "This process %ld with parent %ld\n", (long)getpid(), (long)getppid());
}



Try it like this

:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void main()
{
 int i;
 int n;
 pid_t childpid;

 for(i = 1; i < 4; ++i)
 {
  if((childpid = fork()) <= 0)) /*note that i put a ) at the end of the statement*/
  {
    break;
  }
 }

 fprintf(stderr, "This process %ld with parent %ld\n", (long)getpid(), (long)getppid());
}


Just remember if you have more than on "(" in a statement then you need to add 2 ))
at the end of it.

Tazz13 Oct 10th, 2004 9:45 PM

Thankz but that'z not the problem...the code works correctly...I jsut want each of hte 3 child processes to spawn 1 child of their own.

Thankz

Ooble Oct 11th, 2004 10:29 AM

Sebeq, take a look at that if statement - in your version, there are 3 opening tags and 4 closing tags. He was right.

Sebeq Oct 11th, 2004 11:53 AM

Ahhh yes now i feel like a dummy. I can't see why i didn't see that :P


All times are GMT -5. The time now is 11:14 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC