LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 740|回复: 4

对《Beginning Linux Programming》中一段例程的疑问

[复制链接]
发表于 2005-1-4 16:22:57 | 显示全部楼层 |阅读模式
最近有幸成为一只的Linux的菜鸟,倍感荣幸!于是便找了一本《Beginning Linux Programming》来读,这本书想必好多本论坛的网虫都作为入门读物看过的。我今天在看Processes & Signals着一章的时候,发现有段程序是这样的:
************************************************************************
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
char *message;
int n;
int exit_code;
printf(“fork program starting\n”);
pid = fork();
switch(pid)
{
case -1:
perror(“fork failed”);
exit(1);
case 0:
message = “This is the child”;
n = 5;
exit_code = 37;
break;
default:
message = “This is the parent”;
n = 3;
exit_code = 0;
break;
}
for(; n > 0; n--) {
puts(message);
sleep(1);
}
/*This section of the program waits for the child process to finish.*/
if (pid != 0) {
int stat_val;
pid_t child_pid;
child_pid = wait(&stat_val);
printf(“Child has finished: PID = %d\n”, child_pid);
if(WIFEXITED(stat_val))
printf(“Child exited with code %d\n”, WEXITSTATUS(stat_val));
else
printf(“Child terminated abnormally\n”);
}
exit(exit_code);
}


************************************************************************
编译以后执行的结果是:
$ ./wait
fork program starting
This is the child
This is the parent
This is the parent
This is the child
This is the parent
This is the child
This is the child
This is the child
Child has finished: PID = 1582
Child exited with code 37
$

*************************************************************************
我觉得程序的执行结果应该是:
$ ./wait
fork program starting
This is the parent
This is the child
This is the parent
This is the child
This is the parent
This is the child
This is the child
This is the child
Child has finished: PID = 1582
Child exited with code 37
$
不知是否正确,希望各位给点提示和建议,谢谢!!!
发表于 2005-1-4 16:36:27 | 显示全部楼层
你说的情况也可能出现!
也就是说没有个标准的执行结果!不同的机器或者系统可能出现不同结果!
进程的切换是基于时间片的,可能父进程在执行完fork后用完了时间片,这时进程调度函数调度了子进程来运行!
所以都有可能
 楼主| 发表于 2005-1-4 17:22:23 | 显示全部楼层
说得有道理,不知道还有没有别的解释呢?
发表于 2005-1-4 21:33:00 | 显示全部楼层
对于进程调度来说,父进程与子进程还有其它进程都是一样对待,先调度谁,就执行谁。
 楼主| 发表于 2005-1-5 12:29:18 | 显示全部楼层
谢谢两位!!!
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表