简体   繁体   中英

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

(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.

You are returning before a successful call to _exit, so this behavior is undefined. Try fixing that and see if the problem persists.

A quote from the man page of 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). 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).

Your child process has returned from the function it was created in, so you probably corrupted the stack shared by both threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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