Good example of fork() in a program?

I got some homework about the 'fork()' POSIX system call, and one of the assignments was to write a small example program in C or C++ that uses this system call.

My first idea was:
1
2
3
4
5
6
7
8
#include <unistd.h>

int main()
{
    while(true) {
      fork();
    }
}

:)
But I don't if my professor will appreciate this. In fact, I can't think of a good example of how fork() would be useful without implementing some kind of inter-proccess communication.

Anyways, I'm just asking for your guys opinions, is a fork bomb a valid form of an example program, and if not, do you have any other ideas?
Have you any idea what fork() does?
Well, yeah, it creates an exact copy of a process. The fork bomb was intentional, if that's what you mean.
I can't think of a good example of how fork() would be useful without implementing some kind of inter-proccess communication.
Good point.

You could write something that used the child process to write some text to the screen every 10 seconds, or something like that.

The key idea to gain from this is how to programmatically determine which process is the parent and which is the child, and how to control them separately.
1
2
3
4
5
6
7
8
9
10
int main()
{
    char buf[20];
    for (int i=0; i<5; ++i) {
        sprintf(buf, "file%d", i);
        auto pid = fork();
        // If this is the child then open "buf" as an output file and write something unique to it.
        // Then break out of the loop.       
    }
}

This will demonstrate determining if you're the parent or child after a fork, and it will also show that the child gets a snapshot of the parent's memory image (each child will see a different value in buf).
How about a program that:

1. takes input from a user, then writes it to a text file.
2. sleeps 60 seconds then makes a time-stamped by name backup of the file whenever it changes, if it changes, then loops.

The benefit to using fork for something like that is you don't have to work your backup function into your program at every single level as you continue to grow part 1 from a line capture into something much larger... the backup function is done and it will be its own thing from then on out.

etc
Topic archived. No new replies allowed.