读书人

linux C程序请教下面一个程序为什么

发布时间: 2012-03-28 15:40:03 作者: rapoo

linux C程序,请问下面一个程序为什么会出现Segmentation fault ??
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
pid_t pid;

printf("hello ni hao\n\n");
if ((pid = vfork()) < 0)
printf("fork error\n");
else if (pid == 0)
{
printf("child, pid = %d\n", getpid());

}
else
{
printf("parent, pid = %d\n", getpid());
}

printf("hello\n");
return 0;
}

/*
[root@localhost testing]# ./dir_test
hello ni hao

child, pid = 6948
hello
parent, pid = 6947
hello
Segmentation fault
[root@localhost testing]#
*/

[解决办法]

C/C++ code
...else if (pid == 0)  {  printf("child, pid = %d\n", getpid());    exit(0);    //vfork 保证子进程先运行,在调用exec 或exit 之后父进程才可能被调度运行  }/...
[解决办法]
需要注意fork与vfork的不同:
vfork:父进程和子进程共享虚拟内存,父进程的内存变化(修改,删除)都能影响子进程。
fork:父进程和子进程共享虚拟内存,但使用COW(Copy on Write)技术。但发生内存修改时,会copy一份全新的内存。

这样,由于楼主使用了vfork(它保证子进程先运行),当子进程运行结束退出后销毁了内存,这样父进程的内存也便得无效了,后续的访问当然段错误啦。

使用vfork一定要在子进程启动后调用exec函数族,以便加载一份新的内存。

vfork基本已经废弃,请不要使用。

读书人网 >UNIXLINUX

热点推荐