I am supposed to create a chain of N processes, where N is the command line parameter. Each process creates a child process, prints out its own PID and its parent's PID, and then waits for its child to terminate by calling the wait() function.

Here is my code:

#include <stdio.h>
int main(int argc, char *argv[])
{
 
int number = atoi(argv[1]);
int i;
int pid;
 
for (i=0; i<number-1; i++)
{
 
pid=fork();
if (pid==0)
wait();
 
else
{
printf("I am the child\n");
printf("my pid=%d\n", getpid());
printf("and my parent pid=%d\n", getppid());
}
 
}
}

Any ideas why it's not working properly?

Example output:

[balhoffe1@gator labfork]$ ./lab2 4
I am the child
my pid=6381
and my parent pid=5670
I am the child
my pid=6381
and my parent pid=5670
I am the child
my pid=6382
and my parent pid=6381
I am the child
my pid=6381
and my parent pid=5670
[balhoffe1@gator labfork]$ I am the child
I am the child
my pid=6384
and my parent pid=1
my pid=6382
and my parent pid=1
I am the child
my pid=6383
and my parent pid=1

# if (pid==0)
# wait();
fork() returns 0 in the child, not the parent.

Your if/else is the wrong way round.

it might be because you havent defined pid of type pid_t.

you need to do the following in order to be able to use pid:

#include<sys/types.h>

pid_t pid1;

pid1=fork();

you can then use wait(pid).

I am supposed to create a chain of N processes, where N is the command line parameter. Each process creates a child process, prints out its own PID and its parent's PID, and then waits for its child to terminate by calling the wait() function.

Here is my code:

#include <stdio.h>
int main(int argc, char *argv[])
{
 
int number = atoi(argv[1]);
int i;
int pid;
 
for (i=0; i<number-1; i++)
{
 
pid=fork();
if (pid==0)
wait();
 
else
{
printf("I am the child\n");
printf("my pid=%d\n", getpid());
printf("and my parent pid=%d\n", getppid());
}
 
}
}

Any ideas why it's not working properly?

Example output:

[balhoffe1@gator labfork]$ ./lab2 4
I am the child
my pid=6381
and my parent pid=5670
I am the child
my pid=6381
and my parent pid=5670
I am the child
my pid=6382
and my parent pid=6381
I am the child
my pid=6381
and my parent pid=5670
[balhoffe1@gator labfork]$ I am the child
I am the child
my pid=6384
and my parent pid=1
my pid=6382
and my parent pid=1
I am the child
my pid=6383
and my parent pid=1

Comments
Or it might be because you didn't read the post dates
This question has already been answered. Start a new discussion instead.