Trying to write a simple program that uses pipe/fork to create/manage 1 parent and 4 kid processes. The parent process is supposed to display a main menu like so.
Main Menu:
1. Display children states
2. Kill a child
3. Signal a child
4. Reap a child
5. Kill and reap all children
The code I'm writing now is supposed to create 4 child processes. I'm unsure if I'm setting up the four child processes correctly. I understand fork returns 0 to the child and the PID to the parent. How do I access the parent for these PID values? Where exactly do I set up the menu for the parent process?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#define BUFSIZE 1024
#define KIDS 4
main()
{
//create unnamed pipe
int fd[2];
char buf[BUFSIZE];
if (pipe(fd) < 0)
{
perror("pipe failed");
exit (1);
}
//array of child pids
size_t child_pid[4];
//create 4 proccesses
int i = 0;
for (i = 0; i < KIDS; i++) {
child_pid[i] = fork();
if (child_pid[i]) {
continue;
} else if (child_pid[i] == 0) {
close(fd[0]);
printf("Child %d: pid: %zu", i+1, child_pid[i]);
break;
} else {
printf("fork error\n");
exit(1);
}
}
}
My output is:
Child 1: pid: 0
Child 2: pid: 0
Child 3: pid: 0
Child 4: pid: 0
I'm unsure if I'm setting up the four child processes correctly.
Right, you shouldn't let the children break out of their code block, so change
break;
to
sleep(99); // or whatever you want the child to do
exit(0);
How do I access the parent …?
There's getppid(), if for some reason you need it.
Where exactly do I set up the menu for the parent process?
Do that after the for loop before the end of main, that's where the parent continues execution.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Questions:
Are my processes running in parallel?
I want six processes running in parallel.
How can I sync these processes (parent with five child processes) using semaphores, in an infinite loop? So the output would be: 1 2 3 4 5 reset 1 2 3 4 5 reset etc...
Any simple and understanding semaphore documentation?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
parentWithFiveChildren()
{
printf("1 "); //Parent
fflush(stdout);
int i, status;
for (i = 2; i < 7; i++)
{
sleep(1);
if (fork() == 0) //Child Processes
{
if (i == 6)
{
printf("reset ");
fflush(stdout);
exit(0);
}
printf("%d ", i);
fflush(stdout);
sleep(7);
exit(i); //Exiting child processes
}
}
while ((wait(&status)) > 0)
printf("\a");
return 0;
}
int main(void)
{
parentWithFiveChildren();
}
Output:
1 2 3 4 5 reset
1. Parallelism
No, the processes are not running in parallel (or, at least, they're only running in parallel transiently, and only two processes at a time), but that's only because:
The sleep(1) gives the parent process a long time (at least a second) doing nothing.
The child finishes and exits during that second.
Your printing code in the child is odd; there is effectively no difference between the i == 6 and the other operations. In main(), return 0; and exit(0); are practically the same — there can be differences, but they're obscure and not germane to your code.
You should #include <sys/wait.h> and you should collect the dead children's PID (and status); it would make things clearer to you.
You could also have the children report sleep for a while (say 7 seconds each). That would give you all the child processes 'running' (actually, sleeping) in parallel, and the parent then waits for the children to exit:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
printf("[PARENT] with pid %d\n", getpid());
fflush(stdout);
for (int i = 2; i < 7; i++) // Odd loop conditions, but not wrong
{
sleep(1);
if (fork() == 0)
{
printf("[CHILD] with pid %d from parent with pid %d\n", getpid(), getppid());
fflush(stdout);
sleep(7);
printf("[CHILD] with pid %d exiting with status %d\n", getpid(), i);
exit(i);
}
}
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("%d: child %d exited with status 0x%.4X\n", getpid(), corpse, status);
return 0;
}
Sample output:
$ ./test-forking
[PARENT] with pid 13904
[CHILD] with pid 13905 from parent with pid 13904
[CHILD] with pid 13906 from parent with pid 13904
[CHILD] with pid 13907 from parent with pid 13904
[CHILD] with pid 13908 from parent with pid 13904
[CHILD] with pid 13909 from parent with pid 13904
[CHILD] with pid 13905 exiting with status 2
13904: child 13905 exited with status 0x0200
[CHILD] with pid 13906 exiting with status 3
13904: child 13906 exited with status 0x0300
[CHILD] with pid 13907 exiting with status 4
13904: child 13907 exited with status 0x0400
[CHILD] with pid 13908 exiting with status 5
13904: child 13908 exited with status 0x0500
[CHILD] with pid 13909 exiting with status 6
13904: child 13909 exited with status 0x0600
$
An upgrade to the code would print the time with each line of output too.
2. Killing
Any of the processes (in the set created by the parent) can kill any other process (in the set) that it knows about, using the kill() system call. It really isn't clear whether you want the first child or the last child to kill the parent, or something else. If the first child kills the parent, the first child will be the only child (because of the delays). It also isn't clear why you want to send signals between the processes.
3. Looping
Yes, you could do something — the question is, what are you really after. Simply printing parent and child multiple times doesn't require multiple processes. If you want the parent to say "I'm here", and each child to say "I'm here" periodically, you need to have the children looping and sleeping, and the parent looping and sleeping after all the children have been created. Not hard to do.
question 3). ...Can I put main function in an infinite loop...?
Sure you can:
int main(void)
{
int c=0;
while((c != 'q') && (c != EOF))//loops until c == q (and c!=EOF)
{
c = getchar();//waits until stdin sees a "q", (i.e. from keyboard)
//An EOF (-1) or `q` will exit the loop
//any other input will allow execution flow to continue, 1 loop at a time.
//Add additional forking code here.
//for each loop, spawn a new thread.
//All secondary threads spawned will run parallel to other threads.
}
//exiting here will kill all threads (secondary and primary.)
return 0;
}
1) Yes, your parent process and child are running in parallel after fork,
You can see this by infinite looping child process and printing it's name while parent and other processes are doing the same.
2) Yes, here's how:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/types.h>
#include <signal.h>
int main()
{
pid_t pid;
int i = 0;
if ((pid = fork()) == 0)
{
if ((pid = getppid()) == -1)
{
fprintf(stderr, "child error: getppid()\n");
exit(1);
}
if (kill(pid, 9) == -1)
{
fprintf(stderr, "child error: kill()\n");
exit(1);
}
while (true)
{
printf ("child %d\n", ++i);
}
}
else if (pid == -1)
{
fprintf(stderr, "error: fork()\n");
return 1;
}
while (true)
{
printf("parent %d\n", ++i);
}
return 0;
}
3) If you need that specific pattern, you need interprocess communication and synchronization. Suggest this
Below is an example of the Fork function in action. Below is also the output. My main question has to to do with the a fork is called how values are changed. So pid1,2 and 3 start off at 0 and get changed as the forks happen. Is this because each time a fork happens the values are copied to the child and the specific value gets changed in the parent? Basically how do values change with fork functions?
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
pid1=0, pid2=0, pid3=0;
pid1= fork(); /* A */
if(pid1==0){
pid2=fork(); /* B */
pid3=fork(); /* C */
} else {
pid3=fork(); /* D */
if(pid3==0) {
pid2=fork(); /* E */
}
if((pid1 == 0)&&(pid2 == 0))
printf("Level 1\n");
if(pid1 !=0)
printf("Level 2\n");
if(pid2 !=0)
printf("Level 3\n");
if(pid3 !=0)
printf("Level 4\n");
return 0;
}
}
Then this is the execution.
----A----D--------- (pid1!=0, pid2==0(as initialized), pid3!=0, print "Level 2" and "Level 4")
| |
| +----E---- (pid1!=0, pid2!=0, pid3==0, print "Level 2" and "Level 3")
| |
| +---- (pid1!=0, pid2==0, pid3==0, print "Level 2")
|
+----B----C---- (pid1==0, pid2!=0, pid3!=0, print nothing)
| |
| +---- (pid1==0, pid2==0, pid3==0, print nothing)
|
+----C---- (pid1==0, pid2==0, pid3!=0, print nothing)
|
+---- (pid1==0, pid2==0, pid3==0, print nothing)
Ideally below is how I would like to see it explained as this way makes sense to me. The * are where my main confusion lies. When the child forks for example pid1 = fork(); that creates a process with all the values of the parent, but does it then pass up a value like lets say 1 to the parents pid1? Meaning the child would have pid 1=0, pid2=0 and pid3=0 and the parent then as pid1=2 and pid2 and 3 equal to 0?
System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork()
Fork is a system call and you shouldnt think of it as a normal C function. When a fork() occurs you effectively create two new processes with their own address space.Variable that are initialized before the fork() call store the same values in both the address space. However values modified within the address space of either of the process remain unaffected in other process one of which is parent and the other is child.
So if,
pid=fork();
If in the subsequent blocks of code you check the value of pid.Both processes run for the entire length of your code. So how do we distinguish them.
Again Fork is a system call and here is difference.Inside the newly created child process pid will store 0 while in the parent process it would store a positive value.A negative value inside pid indicates a fork error.
When we test the value of pid
to find whether it is equal to zero or greater than it we are effectively finding out whether we are in the child process or the parent process.
Read more about Fork
int a = fork();
Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.
The child getting 0 returned, and the parent getting the new pid.
Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.
At each fork, only one value is modified - the return value from fork.
First a link to some documentation of fork()
http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html
The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.
So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.
If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().
pid_t pid = fork()
if(pid == 0) {
printf("this is a child: my new unique pid is %d\n", getpid());
} else {
printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}
and below is some inline comments on your code
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
pid1=0, pid2=0, pid3=0;
pid1= fork(); /* A */
if(pid1 == 0){
/* This is child A */
pid2=fork(); /* B */
pid3=fork(); /* C */
} else {
/* This is parent A */
/* Child B and C will never reach this code */
pid3=fork(); /* D */
if(pid3==0) {
/* This is child D fork'ed from parent A */
pid2=fork(); /* E */
}
if((pid1 == 0)&&(pid2 == 0)) {
/* pid1 will never be 0 here so this is dead code */
printf("Level 1\n");
}
if(pid1 !=0) {
/* This is always true for both parent and child E */
printf("Level 2\n");
}
if(pid2 !=0) {
/* This is parent E (same as parent A) */
printf("Level 3\n");
}
if(pid3 !=0) {
/* This is parent D (same as parent A) */
printf("Level 4\n");
}
}
return 0;
}
I think every process you make start executing the line you create so something like this...
pid=fork() at line 6. fork function returns 2 values
you have 2 pids, first pid=0 for child and pid>0 for parent
so you can use if to separate
.
/*
sleep(int time) to see clearly
<0 fail
=0 child
>0 parent
*/
int main(int argc, char** argv) {
pid_t childpid1, childpid2;
printf("pid = process identification\n");
printf("ppid = parent process identification\n");
childpid1 = fork();
if (childpid1 == -1) {
printf("Fork error !\n");
}
if (childpid1 == 0) {
sleep(1);
printf("child[1] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
childpid2 = fork();
if (childpid2 == 0) {
sleep(2);
printf("child[2] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
sleep(3);
printf("parent --> pid = %d\n", getpid());
}
}
return 0;
}
//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398
linux.die.net
some uni stuff
I want to write an UNIX program that creates N child processes, so that the first process creates one child process, then this child creates only one process that is its child, then the child of the child creates another child etc.
Here's my code:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int N=3;
int i=0;
printf("Creating %d children\n", N);
printf("PARENT PROCESS\nMy pid is:%d \n",getpid() );
for(i=0;i<N;i++)
{
pid_t pid=fork();
if(pid < 0)
{
perror("Fork error\n");
return 1;
}
else if (pid==0) /* child */
{
printf("CHILD My pid is:%d my parent pid is %d\n",getpid(), getppid() );
}
else /* parrent */
{
exit(0);
}
}
return 0;
}
The output that I expect is in the form:
Creating 3 children
PARENT PROCESS
My pid is 1234
CHILD My pid is 4567 my parent pid is 1234
CHILD My pid is 3528 my parent pid is 4567
CHILD My pid is 5735 my parent pid is 3528
The output I get in the terminal is
Creating 3 children
PARENT PROCESS
My pid is:564
CHILD My pid is:5036 my parent pid is 564
User#User-PC ~
$ CHILD My pid is:4804 my parent pid is 1
CHILD My pid is:6412 my parent pid is 4804
The problem is that the program doesn't seem to terminate. I should use Ctrl+C to get out of the terminal, which is not normal. Can you help me to fix this issue?
The children die when the parent dies.
In your case the parent exits before all the children have been created.
Try waiting for the children before exiting:
else /* parrent */
{
int returnStatus;
waitpid(pid, &returnStatus, 0); // Parent process waits for child to terminate.
exit(0);
}
try to wait the process with wait(NULL);
pid_t child = fork();
if (child == -1)
{
puts("error");
exit(0);
}
else if (child == 0)
{
// your action
}
else
{
wait(&child);
exit(0);
}
so your father will wait the child process to exit
The proposed cure is correct, but the reason stated is wrong. Children do not die with the parent. The line
CHILD My pid is:4804 my parent pid is 1
clearly indicates that by the time child called getppid() its parent is already dead, and the child has been reparented to init (pid 1).
The real problem is that after the child prints its message, it continues to execute the loop, producing more children, making your program into a fork bomb.
So I am trying do a application which fork()s 2 children.
first does a for(i=1; i<=50000; i++) loop
the second a for(i=50000; i<=100000; i++) loop
the parent does for(asciic=65; asciic<=90; asciic++)-> loop for printing A to Z letters
I need all three to do they're work simultaneous not one after another.
I've looked over the internet and I couldn't found a proper way, all I could find are loops which create the children processes but they do almost the same thing and most are created one after another.
Any help is appreciated.
To be more understood, this is what I've done before posting:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t child_pid,child_pid1;
int i=0;
int stare;
int asciic;
child_pid=fork();
child_pid1=fork();
if (child_pid==0) {
//printf("Father PID: %d -> Child 1: %d\n",getppid(),getpid());
for(i=1; i<=50000; i++){
printf("%d-%d\n",getpid(),i);
}
exit(0);
} else if (child_pid1==0) {
//printf("Father PID: %d -> Child 2: %d\n",getppid(),getpid());
for(i=50000; i<=100000; i++) {
printf("%d-%d\n",getpid(),i);
}
exit(0);
} else {
//printf("PID-ul procesului parinte: %d\n", getpid());
pid_t rez=waitpid(child_pid,&stare,WNOHANG);
pid_t rez1=waitpid(child_pid1,&stare,WNOHANG);
while(rez==0 || rez1==0){
for(asciic=65; asciic<=90; asciic++){
printf("%d- %c\n",getpid(),asciic);
}
rez=waitpid(child_pid,&stare,WNOHANG);
rez1=waitpid(child_pid1,&stare,WNOHANG);
}
}
return 0;
}
If I comment out the loops I can see that the children have different PIDs, 1 child has the right parent PID and other it has other parent PID.
Your 2 lines with forks:
child_pid=fork();
child_pid1=fork();
do not create 2 children, but three: the parent creates a first child in the first fork(). From that moment there are 2 processes: parent and child. And each of them executes the second fork(). You will have in total 1 parent, 2 children and 1 grandchild.
In order to have just 1 parent and 2 children, you will have to:
pid1 = fork();
if (pid1 < 0) {
/* Error in fork() */
} else if (pid1 == 0) {
/* first child */
exit(0);
}
pid2 = fork();
if (pid2 < 0) {
/* Error in fork() */
} else if (pid2 == 0) {
/* second child */
exit(0);
}
/* parent */
Moreover, even when your code is correct, you cannot "see" if the processes are running concurrently or not just looking at their outputs. In fact, even if there are multiple processes executing "at the same time", you may see that one of the processes finishes before another one starts. That is because typically the kernel does time multiplexing to offer each child some CPU time. You can see concurrency if the processes take longer to complete, for example adding some sleep().
The problem is here:
child_pid=fork();
child_pid1=fork(); // This line will be executed by both parent and first child!!!
You need to move the second fork into the parent part of the first if, and then have a separate if for the second child.
fork() returns the pid_t of the child to the caller (parent), or -1 if it failed. In the child, 0 is returned. You can simply test
if (fork())
{
//do one thing
}
else
{
//do something else
}
I'm starting to learn some C and while studying the fork, wait functions I got to a unexpected output. At least for me.
Is there any way to create only 2 child processes from the parent?
Here my code:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main ()
{
/* Create the pipe */
int fd [2];
pipe(fd);
pid_t pid;
pid_t pidb;
pid = fork ();
pidb = fork ();
if (pid < 0)
{
printf ("Fork Failed\n");
return -1;
}
else if (pid == 0)
{
//printf("I'm the child\n");
}
else
{
//printf("I'm the parent\n");
}
printf("I'm pid %d\n",getpid());
return 0;
}
And Here is my output:
I'm pid 6763
I'm pid 6765
I'm pid 6764
I'm pid 6766
Please, ignore the pipe part, I haven't gotten that far yet. I'm just trying to create only 2 child processes so I expect 3 "I'm pid ..." outputs only 1 for the parent which I will make wait and 2 child processes that will communicate through a pipe.
Let me know if you see where my error is.
pid = fork (); #1
pidb = fork (); #2
Let us assume the parent process id is 100, the first fork creates another process 101. Now both 100 & 101 continue execution after #1, so they execute second fork. pid 100 reaches #2 creating another process 102. pid 101 reaches #2 creating another process 103. So we end up with 4 processes.
What you should do is something like this.
if(fork()) # parent
if(fork()) #parent
else # child2
else #child1
After you create process , you should check the return value. if you don't , the seconde fork() will be executed by both the parent process and the child process, so you have four processes.
if you want to create 2 child processes , just :
if (pid = fork()) {
if (pid = fork()) {
;
}
}
You can create n child processes like this:
for (i = 0; i < n; ++i) {
pid = fork();
if (pid > 0) { /* I am the parent, create more children */
continue;
} else if (pid == 0) { /* I am a child, get to work */
break;
} else {
printf("fork error\n");
exit(1);
}
}
When a fork statement is executed by the parent, a child process is created as you'd expect. You could say that the child process also executes the fork statement but returns a 0, the parent, however, returns the pid.
All code after the fork statement is executed by both, the parent and the child.
In your case what was happening was that the first fork statement created a child process. So presently there's one parent, P1, and one child, C1.
Now both P1 and C1 encounter the second fork statement. The parent creates another child (c2) as you'd expect, but even the child, c1 creates a child process (c3). So in effect you have P1, C1, C2 and C3, which is why you got 4 print statement outputs.
A good way to think about this is using trees, with each node representing a process, and the root node is the topmost parent.
you can check the value as
if ( pid < 0 )
process creation unsuccessful
this tells if the child process creation was unsuccessful..
fork returns the process id of the child process if getpid() is used from parent process..
You can create a child process within a child process. This way you can have 2 copies of the original parent process.
int main (void) {
pid_t pid, pid2;
int status;
pid = fork();
if (pid == 0) { //child process
pid2 = fork();
int status2;
if (pid2 == 0) { //child of child process
printf("friends!\n");
}
else {
printf("my ");
fflush(stdout);
wait(&status2);
}
}
else { //parent process
printf("Hello ");
fflush(stdout);
wait(&status);
}
return 0;
}
This prints the following:
Hello my friends!