Reputation: 1419
Can someone help me with this small problem please? I am trying to create a fork bomb and record how many processes a computer creates before something weird happens, but I can't figure out how to write the processes into a text file. I looked around the internet and couldn't find a solution for my problem and I tried doing different things but that didn't work with me also. If you guys can help me out on this matter that would be awesome! Here's my code so far (far from perfect, I know.. D: ).
while(1)
{
fork(); // Fork bomb
write(fd, '\n', sizeof(buf));
}
Thanks in advance
Upvotes: 0
Views: 196
Reputation: 1742
This is a bit complex. I'm writing this answer just for the sake of completeness(and fun!).
Use a process as the "master process". (The easiest way is using the starting process.) Each time a new process is created, a signal(you can use SIGUSR1) would be sent to the master process, so the master process can increment its process counter. (note that incrementing the counter in every process wouldn't work because their memory are not shared.) Once fork() has failed, another signal is sent to the master. Once all children have failed(a child would signal the failure only once and the master would have a failure counter in addition to the process counter), the master will write the process counter to the file, and kill all processes in its process group(kill() can kill not only a single process but also a process group).
Cautions:
You may need to use nice() to avoid the children from preventing the master to execute.
In order to prevent the children from forking again before all children are killed, you may need to suspend the children before terminating them.
Upvotes: 1
Reputation: 118340
Open a file for write+append.
Each forked process will inherit the file descriptor.
In each forked child process, write a single null byte to the file descriptor.
When everything crashes, the size of the file, in bytes, will tell you how many processes were started.
Upvotes: 1