当前位置: 技术问答>linux和unix
fork问题请教!!
来源: 互联网 发布时间:2016-10-10
本文导语: #include #include #include void main() { pid_t pid; char *msg = (char*) malloc( 20 * sizeof(char) ); int k; printf("Process Creation Studyn"); pid = fork(); if(0 == pid) { msg = "Child process is r...
#include
#include
#include
void main()
{
pid_t pid;
char *msg = (char*) malloc( 20 * sizeof(char) );
int k;
printf("Process Creation Studyn");
pid = fork();
if(0 == pid)
{
msg = "Child process is running! n";
k = 3;
}
else if(-1 == pid)
{
perror("Process creation failedn");
}
else
{
msg = "Parent process is running! n";
k = 5;
}
while( k > 0)
{
puts(msg);
sleep(1);
printf("k = %d, &k = %xn", k, &k);
k--;
}
free(msg);
exit(0);
}
打印出来的结果是:
Process Creation Study
Parent process is running!
Child process is running!
k = 5, &k = bfcf9594
Parent process is running!
k = 3, &k = bfcf9594
Child process is running!
k = 4, &k = bfcf9594
Parent process is running!
k = 2, &k = bfcf9594
Child process is running!
k = 3, &k = bfcf9594
Parent process is running!
k = 1, &k = bfcf9594
k = 2, &k = bfcf9594
Parent process is running!
k = 1, &k = bfcf9594
Segmentation fault
问题是:
既然 fork创建的子进程是copy其父进程的资源的话。
然后,父亲跟儿子都有各自独立的资源。(表达的可能不准确)
那么,为什么,父子进程执行下面的代码时:
while( k > 0)
{
puts(msg);
sleep(1);
printf("k = %d, &k = %xn", k, &k);
k--;
}
&k = bfcf9594 都是同样的值了?我可能错误的认为父亲进程中的K的地址值应该相同,
儿子进程中k的地址值是相同的,而父子不相同!
为什么? 谢谢!
|
我想我找到答案了。。。。
http://www.linuxsir.org/bbs/thread222454.html
见这个帖子~~!
http://www.linuxsir.org/bbs/thread222454.html
见这个帖子~~!
|
这个是否跟fork的copy-on-write技术有关!
|
创建进程的时候子进程好像不拷贝父进程的数据区