N
newgoat
I just wrote a short program to see process switch when sleep() is
invoked within a process. The code is as follows:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(void){
pid_t f;
f = fork();
if(f < 0){
printf("Failed to fork\n");
_exit(1);
}
else if(f == 0){
int i;
printf("\nChild: PID is %d\n", getpid());
for(i = 0; i < 10; i++){
printf("c ");
if(i == 5)
sleep(2);
}
printf("\n");
_exit(0);
}
else{
int j;
printf("\nParent: PID is %d\n", getpid());
for(j = 0; j < 10; j++){
printf("p ");
}
printf("\n");
}
return 0;
}
The output is : (Case 1)
Child: PID is 11059
Parent: PID is 11058
p p p p p p p p p p
user@localhost:~$ c c c c c c c c c c
If I commented the if...sleep(2) lines above (two lines),
the output would be: (Case 2)
Child: PID is 11068
c c c c c c c c c c
Parent: PID is 11067
p p p p p p p p p p
In Case 1, I expected the child process to print five c's (because
the child process does not start sleeping until i = 5) then sleep for 2
seconds,
during which time the parent process executes its own block of code.
But the real output suggests otherwise. Why is that?
Thanks in advance.
invoked within a process. The code is as follows:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(void){
pid_t f;
f = fork();
if(f < 0){
printf("Failed to fork\n");
_exit(1);
}
else if(f == 0){
int i;
printf("\nChild: PID is %d\n", getpid());
for(i = 0; i < 10; i++){
printf("c ");
if(i == 5)
sleep(2);
}
printf("\n");
_exit(0);
}
else{
int j;
printf("\nParent: PID is %d\n", getpid());
for(j = 0; j < 10; j++){
printf("p ");
}
printf("\n");
}
return 0;
}
The output is : (Case 1)
Child: PID is 11059
Parent: PID is 11058
p p p p p p p p p p
user@localhost:~$ c c c c c c c c c c
If I commented the if...sleep(2) lines above (two lines),
the output would be: (Case 2)
Child: PID is 11068
c c c c c c c c c c
Parent: PID is 11067
p p p p p p p p p p
In Case 1, I expected the child process to print five c's (because
the child process does not start sleeping until i = 5) then sleep for 2
seconds,
during which time the parent process executes its own block of code.
But the real output suggests otherwise. Why is that?
Thanks in advance.