C: Exec/fork > Defunct processes

Frank Vilea picture Frank Vilea · Jul 16, 2011 · Viewed 17.1k times · Source

I'm want to create a lot of child processes using the fork > exec procedure. Many processes are ending very fast (in less than two minutes, some even earlier).

My first problem is, I put the spawn process into the background with

./spawnbot > logging.txt
[CTRL+Z]
bg 1
disown

So far so good. Now I don't see any of the spawnbot's messages anymore and they go straight into the logging.txt. However, whenever a new child is created I see all the info about that child in my console again.. I now wanted to start each child with it's own pipe - is there a better way to not have children post their output messages all over the console? Should I just redirect it to /dev/null or is this done with some flag in C?

Secondly, all the children don't really get killed. I have a lot of processes in my ps -ef. What can I do about that? How do I d

Answer

Paul picture Paul · Jul 16, 2011

First your second question!

Your children stay in 'zombie' mode because the kernel thinks you might still want to retrieve a return value from them..

If you have no intention to get return values from your child processes, you should set the SIGCHLD signal handler in the parent process to SIG_IGN to have the kernel automatically reap your children.

signal(SIGCHLD, SIG_IGN);

The first question depends a it on your implementation..

But general speaking, just after you fork() you should use close() to close the old file descriptors for 0 and 1 and then use dup2() to set them to your wanted values.. No time for an example right now, but hope this pushes you in the right direction..