Alex
Alex

Reputation: 2299

How to take advantage of each process when using two fork()'s in C

So, I've been trying to understand forks, and although I understand the basics (ie. another process gets created with a copy of the original data when we use fork()), I can't really grasp actually doing things with these processes that are created.

For example: I have to write a program that will call fork() twice to create 4 processes in total. When one process is created I have to print out the pid with getpid(). After printing out four ID's, my program is supposed to print a single letter 10 times.

For example, parent 1 will print 'A', child 1 will print 'B', child 2 will print 'C' and the parent of that will print 'D'. To do this, I have to use putchar(ch); and flush the output with fflush(stdout).

This means the output will look like this:

Process created, ID: 3856
Process created, ID: 3857
Process created, ID: 3858
Process created, ID: 3859
AAAAAABBBBBBBCDCDCDCDCDCDCBBBDCDCAAAADCD

So far, I've gotten the four processes to print with this code:

 int main(void) {
     pid_t child1, child2;
     child1 = fork();
     child2 = fork();
     printf("Process created. ID: %d\n", getpid());
}

But I don't know how to use wait() to have everything print out randomly, after I have printed the ids.

To get everything I need to print out to be a "random mess," what should I do? Should I call functions like this?

// in main
for(int i = 0; i < 10; ++i) {
    char_parent1();
    char_child1();
    char_parent2();
    char_child2();
}
return 0;
}

void char_parent1()
{
    putchar('A');
    fflush(stdout);
}

void char_child1()
{
    putchar('B');
    fflush(stdout);
}

// and so on for char_parent2() and char_child2()

In that case, if my professor says I have to basically print things out concurrently and randomly, then why should I be using wait()?

Upvotes: 1

Views: 320

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

Each process needs to know which letter it is supposed to print. That means you have to analyze the values in child1 and child2. For example, one process has two zeros; it might print D.

Arguably, each process needs to know whether it is a parent or not. If it is not a parent, it can simply exit after printing 10 copies of its letter, each followed by a fflush(). If it is a parent, after waiting for its children to die, it should exit. This means that the original process will exit last. It could usefully output a newline after its last child has died. You might or might not print diagnostic information about dead children as you go.

Upvotes: 2

Related Questions