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.

thanks! that helped alot.

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

commented: Or it might be because you didn't read the post dates -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.