简体   繁体   English

Linux中的C程序中的分段错误

[英]segmentation fault in c program in linux

I am getting segmentation fault in the following program. 我在以下程序中出现分段错误。 Why? 为什么? And how to resolve it? 以及如何解决呢?

#include <stdio.h>
main()
{
    int pid;
    printf("I'm the original process with PID %d and PPID %d.\n", getpid(),getppid());
    pid=vfork();
    if (pid!=0)
    {
         printf("I'm the parent process with PID %d and PPID %d.\n",getpid(),getppid());
         printf("My child's PID is %d.\n", pid);
    }
    else  
    {
         printf("I'm the child process with PID %d and PPID %d.\n",getpid(),getppid());
    }
}

Output: 输出:

I'm the original process with PID 18563 and PPID 18500.
I'm the child process with PID 18564 and PPID 18563.
I'm the parent process with PID 18563 and PPID 18500.
My child's PID is 18564.
Segmentation fault

From vfork man page vfork手册页

(From POSIX.1) The vfork() function has the same effect as fork(2), 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(2) or one of the exec(3) family of functions. (来自POSIX.1)vfork()函数的作用与fork(2)相同,不同之处在于,如果由vfork()创建的进程修改了除用于存储数据的pid_t类型变量以外的任何数据,则该行为未定义从vfork()返回值,或者从调用vfork()的函数返回,或者在成功调用_exit(2)或exec(3)系列函数之一之前调用任何其他函数。

You are returning before a successful call to _exit, so this behavior is undefined. 你成功调用_exit 之前回来,所以这种行为是不确定的。 Try fixing that and see if the problem persists. 尝试解决该问题,然后查看问题是否仍然存在。

A quote from the man page of vfork : vfork手册页中的引文:

vfork() differs from fork(2) in that the calling thread is suspended until the child terminates (either normally, by calling _exit(2), or abnormally, after delivery of a fatal signal), or it makes a call to execve(2). vfork()与fork(2)的不同之处在于,调用线程被挂起,直到子级终止(正常情况下,通过调用_exit(2),或者在传递致命信号后异常终止),或者它调用execve( 2)。 Until that point, the child shares all memory with its parent, including the stack. 在此之前,子级与父级共享所有内存,包括堆栈。 The child MUST NOT RETURN FROM THE CURRENT FUNCTION or call exit(3), but may call _exit(2). 子级不得从当前函数返回或调用exit(3),但可以调用_exit(2)。

Your child process has returned from the function it was created in, so you probably corrupted the stack shared by both threads. 您的子进程已从创建该函数的函数返回,因此您可能破坏了两个线程共享的堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM