I am given the task of creating this process tree in C using fork, if and else:

|___2__   |
|_4_   |  |_3_
|   |  |  |   |

Or as a pstree like drawing:


Is this code correct?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {

        // 1
            // 2
                // 4
            // 3}

    return 0;

closed as unclear what you're asking by Gilles, vonbrand, jimmij, mdpc, Runium Jan 12 '16 at 2:10

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    The question is unclear. This is clearly a homework problem: what were you give, and what do you have to find? – gardenhead Jan 11 '16 at 23:20
  • Hmm - i need to programme this process tree using only fork() – Altair64 Jan 11 '16 at 23:21
  • Hi. It does not help if you use a non standard way to make a graph. Have a look at the output of pstree -ap to see how PIDs and relations are normaslly displayed. Also: Can't you just print out the pid that is returned by fork? You could use pstree to check your assumptions. – joepd Jan 11 '16 at 23:22
  • Ok thank you. I think that our lecturer need to specify what he wants from us :) I have to create a process tree using fork() and if, else in C. The proc tree have to look like is shown above. – Altair64 Jan 11 '16 at 23:23
  • Here is similar problem but different process tree. stackoverflow.com/questions/24082775/… – Altair64 Jan 11 '16 at 23:28

OK I understand your question now. Your answer is correct. All I will say is that you can just do


for the final forks instead of

if (fork()) {}
else {}
  • Could you elaborate The order of what? – gardenhead Jan 12 '16 at 0:53
  • No it can't. Besides the numbers don't matter -- only the structure of the tree. – gardenhead Jan 12 '16 at 1:09
  • Guess we're talking past each other. The point is that there is no guarantee 3 is forked before 4. – Runium Jan 12 '16 at 2:04
  • I don't think that diagram is meant to have a timeline to it. Whether 3 or 4 is forked first, the tree structure will be the same. – gardenhead Jan 12 '16 at 2:11
  • Yes, guess not. But then there is those dangling lines. Are those the forks and the pstree drawing wrong? (I added that one but perhaps I should not have. Did it as comments does not support that kind of drawings ...) – Runium Jan 12 '16 at 2:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.