• 13
• 18
• 19
• 27
• 10

# fork issue

This topic is 1114 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello,

I wish, under Linux, to launch an external application from my application. The launch should be not blocking for the main application, similar to what can be achieved under Windows with ShellExecute.

So, under Linux, I do:

printf("Parent about to start child process...\n");
if(fork()==0)
{
printf("Child started.\n");
execl("executableName","executableName","argument1",(char*) 0);
printf("Child ended.\n");
exit(0);
}
printf("Child process started, parent resuming..\n");


Above code works, but there are two issues:

1. Why does my child never return (i.e. "Child ended." is never printed, even if the launched executable ended)?

2. My main application, when ending, creates a seg fault.

Thanks for any insight!

##### Share on other sites

1. Why does my child never return (i.e. "Child ended." is never printed, even if the launched executable ended)?

The manual page for execve (for which execl is a front-end) states:

execve() does not return on success, and the text, data, bss, and stack of  the calling process are overwritten by that of the program loaded.[...]

That means that the program containing "printf("Child ended.\n") is replaced by the program denoted by "executableName". Hence anything written behind execve and companions is invoked if and only if execve has failed.

Edited by haegarr

##### Share on other sites

Thanks for the fast reply!

Ok, that makes sense!

Any why is my main application causing a seg fault (and only if fork and execl was called previously)? Does the fork/execl instructions change something in my main application?

##### Share on other sites

the fork() call copies the entire memory map of the calling process into the new process, and inherits file handles. execve() if i remember correctly has similar scemantics, but immediately replaces the old process with a new one's image and then excutes that, instead. Certain things are not inherited though, such as memory locks, signal masks, and async I/O.

This may or may not be something you want, and the child process might be closing a resource that the parent process is still trying to access, e.g. calling close() or freopen() on a file descriptor.

I suggest you read thoroughly the manpages of fork (man 2 fork) and execve, also perhaps system() and use gdb or similar to properly debug the program, i always find that seeing the stack backtrace (gdb bt) helps a lot.

Good luck!

Edited by braindigitalis

##### Share on other sites

Thanks a lot for the detailed explanation!

I'll try my luck with your suggestions.