LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to debug fork() (https://www.linuxquestions.org/questions/programming-9/how-to-debug-fork-711697/)

charlitos 03-15-2009 03:06 AM

How to debug fork()
 
Im writing a program which is doing some multitasking by using fork(), but I have no clue of how to debug it so that I can see what the child process is doing, I can only keep track of the parent process which is communicating with the child through a pipe, it also has a line to wait for the child process to finish, but I never see whats happening with fork() == 0. I know its a different process running somewhere else in memory but how can keep track of both of them ? I dont know how I would do it since both processes will be using the same variable names...

The only thing I get from the child(while my debugger is running the parent process) is its response, but i want to know how it decides to send me that response...

Sergei Steshenko 03-15-2009 04:04 AM

"print" statement (in this case with own PID) is still a _major_ debugging tool.

To the same extent, log files whose names are based on PID also are.

wje_lq 03-15-2009 06:13 AM

If you're running Linux kernel 2.6, gdb will give you complete control. Go here for details.

(This also applies if you're running HP-UX 11.x or later.)

If you're running Linux kernel 2.4 or something else, I'll quote from the above link, and insert my comment in red:
Quote:

However, if you want to debug the child process there is a workaround which isn't too painful. Put a call to sleep in the code which the child process executes after the fork. It may be useful to sleep only if a certain environment variable is set, or a certain file exists, so that the delay need not occur when you don't want to run GDB on the child. While the child is sleeping, use the ps program to get its process ID. Or, just before the call to sleep, printf("%d\n",getpid());. Then tell GDB (a new invocation of GDB if you are also debugging the parent process) to attach to the child process (see section 4.7 Debugging an Already-running Process). From that point on you can debug the child process just like any other process which you attached to.
Remember that if you're running Linux 2.6, you can avoid the previous quotation and get complete control.

If you're going to be doing stuff like this, it would do you good to browse through the complete online gdb documentation. If you use that documentation frequently, as I do, you might wish to download it from here (html tarball) or here (other formats).

Hope this helps.


All times are GMT -5. The time now is 08:04 PM.