+ 3

vfork() gives "Segmentation fault (core dumped)" after code is executed

Hi, I have tried to execute a simple example of vfork() to understand its working. Issue: The code completed execution as expected but terminates with a "Segmentation fault (core dumped)" error. I have read that behavior of vfork() is quite unpredictable. Can someone explain me where did I go wrong? Code: #include <sys/types.h> #include <unistd.h> #include <stdio.h> int main() { int pid = vfork(); //creating the child process if (pid == 0) //if this is a child process { printf("\nParent process is paused..."); printf("\nChild process started...\n"); } else//parent process execution { printf("\nParent process resumed...\n"); } return 0; } Output: shweta@ubuntu:~$ ./a.out Parent process is paused... Child process started... Parent process resumed... Segmentation fault (core dumped) shweta@ubuntu:~$

4th Apr 2021, 8:10 AM
Shweta Gare
Shweta Gare - avatar
2 Respostas
+ 1
It is because returning from the function where vfork() is called or calling any other function before successfully calling *_exit()* or one of the *exec()* family of functions leads to undefined behaviour. You can see this in the manpage of vfork() 👇 https://man7.org/linux/man-pages/man2/vfork.2.html
4th Apr 2021, 9:17 AM
Arsenic
Arsenic - avatar
+ 1
Part of your problem is that the parent process is NOT paused. You need to wait on the child process to complete before exiting.
4th Apr 2021, 2:06 PM
A S Raghuvanshi
A S Raghuvanshi - avatar