- 论坛徽章:
- 0
|
大大们好,新手刚刚学习linux下的编程。
碰到一个问题,特向大大们请教:
#include "apue.h"
#include <sys/wait.h>
void
pr_exit(int status)
{
if (WIFEXITED(status))
printf("normal termination, exit status = %d\n",
WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("abnormal termination, signal number = %d%s\n",
WTERMSIG(status),
#ifdef WCOREDUMP
WCOREDUMP(status) ? " (core file generated)" : "");
#else
"");
#endif
else if (WIFSTOPPED(status))
printf("child stopped, signal number = %d\n",
WSTOPSIG(status));
}
------------------------------------
#include "apue.h"
#include <sys/wait.h>
int
main(void)
{
pid_t pid;
int status;
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0) /* child */
exit(7);
if (wait(&status) != pid) /* wait for child */
err_sys("wait error");
pr_exit(status); /* and print its status */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0) /* child */
abort(); /* generates SIGABRT */
if (wait(&status) != pid) /* wait for child */
err_sys("wait error");
pr_exit(status); /* and print its status */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0) /* child */
status /= 0; /* divide by 0 generates SIGFPE */
if (wait(&status) != pid) /* wait for child */
err_sys("wait error");
pr_exit(status); /* and print its status */
exit(0);
}
------------------------------
RESULTS:
$ ./a.out
normal termination, exit status = 7
abnormal termination, signal number = 6 (core file generated)
abnormal termination, signal number = 8 (core file generated)
关于linux下的进程创建机制我也有一定的理解。
问题1:
linux采用的是copy-on-write机制,那么是不是说上面的例子中,子进程和父进程代码都是共享的一份代码喽?毕竟,没有变量的改写之类的啊。。。
问题2:
对于上面的代码,关于子进程的判断的时候,就只有一句代码:if (pid == 0) ...
我理解的是, 1》 exit(7); 2》 abort(); 3》status /= 0;
这三句代码毕竟是从上向下依次执行的,那么就如果问题1中的假设成立的话,那么exit(7);将是最先被执行的代码,剩下的2》3》都不会被执行。
这里我最难理解的就是共享一份代码,linux是依据什么去判断那三个不同的进程,并出现不同的执行结果呢?
============================================================
大大们linux下编程有经验的多,希望能帮一帮小菜鸟,大家一起进步。谢谢大大们了。。
|
|
|