1

当我尝试以下代码段时,我收到一个称为堆栈粉碎的错误。这个潜在的错误可能是什么原因?有人可以解释一下吗?

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int glob=88;
int main()
{
    int loc=2;
    pid_t pid=vfork();
    if(pid==0)
    {
        printf("Inside child");
        glob++;
        loc++;
        printf("%d %d" ,glob,loc);
    }
    else
    {
        printf("Inside parent");
        glob++;
        loc++;
        printf("%d %d",glob,loc);
    }
}

我运行这段代码时的输出是这样的

user018@sshell ~ $ gcc one.c
user018@sshell ~ $ ./a.out
Inside child89 3Inside parent90 945733057*** stack smashing detected ***: a.out
- terminated
a.out: stack smashing attack in function <unknown> - terminated
KILLED
4

3 回答 3

1

Linux 手册页(和 POSIX):

vfork() 函数与 fork(2) 具有相同的效果,除了如果由 vfork() 创建的进程修改了用于存储来自 vfork() 的返回值的 pid_t 类型的变量以外的任何数据,则行为未定义,或从调用 vfork() 的函数返回,或在成功调用 _exit(2) 或 exec(3) 系列函数之一之前调用任何其他函数。

您正在修改数据并从vfork被调用的函数返回——这两者都会导致未定义的行为。vfork不等于fork,你可以在vforkd child 中做的事情非常非常有限。它应该只在非常特殊的情况下使用,基本上是当你唯一需要在孩子身上做的事情是exec别的事情时。

有关完整详细信息,请参见操作系统的手册页。

于 2013-07-29T05:39:11.663 回答
1

vfork()用于创建新进程而不复制父进程的页表。所以你不能修改子进程中的变量,因为它们已经不存在了。改为使用fork()

还有一件事,最好\n在末尾添加一个,printf()因为stdout默认情况下是行缓冲的。

于 2013-07-29T05:39:37.423 回答
0

1) I would definitely add a "return 0", since you declared "int main()".

2) If you wanted to disable the warning, use -fno-stack-protector in your compile line.

3) If you wanted to debug where the error is coming from, use "-g" in your compile line, and run the program from gdb (instead of running ./a.out).

My closest to "what's wrong" is this man page about vfork():

http://linux.die.net/man/3/vfork

The vfork() function shall be equivalent to fork(), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.

For Linux, just use "fork()", and I think you'll be happy :)

于 2013-07-29T05:39:44.100 回答