I'm a bit confused with the creation of processes with fork()
, sleep()
and wait()
in c. Take the following piece of code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
void childProcess(void);
void childProcess(void)
{
for(int i = 0; i < 5; i )
{
printf("pid: %d email: myemail\n", getpid());
sleep(1);
}
}
int main(int argc, char *argv[])
{
for (int i = 0; i < 5; i )
{
pid_t childpid;
if ((childpid = fork()) == 0)
{
childProcess();
exit(0);
}
}
int status;
while (wait(&status) > 0)
{
}
return 0;
}
After this piece of code has been executed,executes processes but does not remove repetitions from 5 processes. I'm a little confused with the process.
The initial process creates 5 child processes, and waits for them to finish. Each child process performs 5 repetitions, where in each repetition:
Prints the message pid: PID email: USER_EMAIL where PID is the child PID of the process, while USER_EMAIL is the email
Suspends its operation for 1 second (at a time) with the sleep call
The parent process prints the children's PIDs when they are finished
P.S I EDIT THE CODE
CodePudding user response:
@mixalispetros, you have multiple things to fix, and they all have to be fixed together for your code to work as intended.
exit(0);
for (int i = 0; i < 5; i ) {
wait(NULL);
}
The process ends on exit(0)
. wait
is never called.
if (fork() == 0) {
// what code runs here? The code in the new process
}
What code runs within the fork()
conditional? The new process's code. Which process should run wait()
? The original process. So in addition to being after an exit
, the wait()
is also in the wrong process.
Where to move it? The for
loop wait()
s for 5 child processes. Why would there be 5 child processes for which to to wait()
? Because we had already started all 5 child processes before we went into our loop of 5 wait()
s.
The wait()
s must happen not just outside the child process conditional block, but also outside the loop around the call to fork()
.
I'm a bit confused with the creation of processes with fork(), sleep() and wait() in c
It is confusing. Refer to the documentation often to keep it straight.
Remember, fork()
returns twice - in the original process (returning the process ID of the new process), and in the new process (returning 0
). wait()
, will wait for the next child process to exit.
In summary, put the wait
loop outside the loop that fork()
s child processes. This will also move it ouside the block of code that executes in the child
process.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
// this loop creates 5 processes
for (int i = 0; i < 5; i ) {
if (fork() == 0) {
printf("Child %d, PID %d\n", i, getpid());
sleep(i);
exit(0);
}
}
// now, all subprocesses were started
// wait for the same number of child processes to end
for (int i = 0; i < 5; i ) {
wait(NULL);
}
}