05-25-06 12:16 AM
On 2006-05-24, newgoat@gmail.com <newgoat@gmail.com> wrote:
> I just wrote a short program to see process switch when sleep() is
> invoked within a process. The code is as follows:
You forgot to flush the stdout buffer.
>
> #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.
>
fflush will solve your problem - e.g., run 'patch' on your C file with this
diff -u output:
--- old.c 2006-05-24 12:34:53.000000000 -0600
+++ new.c 2006-05-24 12:40:22.000000000 -0600
@@ -19,6 +19,7 @@
printf("\nChild: PID is %d\n", getpid());
for(i = 0; i < 10; i++){
printf("c ");
+ fflush(stdout);
if(i == 5)
sleep(2);
}
@@ -33,6 +34,7 @@
printf("\nParent: PID is %d\n", getpid());
for(j = 0; j < 10; j++){
printf("p ");
+ fflush(stdout);
}
printf("\n");
}
--
*** Posted via a free Usenet account from http://www.teranews.com ***
[ Post a follow-up to this message ]
|