关于fork的小问题

来源:百度知道 编辑:UC知道 时间:2024/07/04 10:00:49
我的程序:
#include<stdio.h>
main()
{
int pid1,pid2;
int i,j,k;
if((pid1=fork())==0){
for(i=0;i<3;i++)
printf("hello\n");
}
if((pid2=fork())==0){
for(j=0;j<3;j++)
printf("every\n");
}
if(pid1>0|pid2>0){
for(k=0;k<3;k++)
printf("one\n");
}
}
此程序执行后貌似是按顺序执行的,父进程和子进程是分别独立地进入就绪队列等待调度的,那么谁先得到调度是不确定的,那么输出应该是不定的,也就是乱的,请问这个程序该怎么改才能开出他们是同时执行的。

看以下程序

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
pid_t pid;
char *msg;
int n;
printf("program starting\n");
pid = fork();
switch(pid)
{
case -1:
exit(1);
case 0:
msg = "this is child";
n = 3;
break;
default:
msg = "this is parent";
n = 6;
break;
}

for(; n > 0; n--)
{
puts(msg);
sleep(1);
}
exit(0);
}

运行结果:
program starting

this is parent

this is child

this is parent

this is child

this is parent

this is child

this is parent

this is parent

this is parent

正如楼上所