Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Nov 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    processes created with fork

    I want to create a process named D which will create 3 other processes called A, B and C. I am using fork like this example:

    int main() {
    pid_t pida,pidb,pidc;
    pida = fork();
    pidb = fork();
    pidc = fork();
    }

    But my question is how I will discriminate the three processes in my programme. I mean that in the parent process i will have three pid numbers (pida, pidb, pidc) but i won’t know them in advance (The system will give these codes when running the programme). The only think i know is that they will be just positive numbers.
    For example if i want to do something in process B i am gonna put an “if” but what i am gonna check to realize that i am in process B before to enter the “if” bronchus?

  • #2
    New to the CF scene
    Join Date
    Nov 2008
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Hi,

    I believe you are going to get more than three processes... Because you have a fork() called after another, the child process from the first fork() is going to call fork() again, etc. So, I recommend you do the following if you only want three child processes. And to distinguish each of the child processes, use an integer variable.

    Example:

    int main() {

    pid_t pid = 1;
    int i = 0;

    for (; i < 3 && pid != 0; i++) {
    pid = fork();
    }

    if (pid != 0) { /* this is the parent process */
    .....
    }
    else { /* child processes */
    if (i == 0) { } /* this is the first child process */
    else if (i == 1) /* this is the second child process */
    else if (i == 2) /* this is the third child process */
    else { } /* not valid ? */
    }
    ....

    Integer 'i' will be unique for each child process because it inherits the parent process at the instant it was spawned.

    I haven't been doing fork() programming in a while but this is the concept I would use. Hope this helps.

    - member887


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •