how to create two processes from a single Parent

2020-06-21 07:34发布

I know I'm going to need to use fork(), but this just creates a single child process. Do i simply call fork again from within the child process? Also, I need them to communicate through a signal or pipe, which is easier to implement and what do i need to know for doing that (functions, etc..)

8条回答
够拽才男人
2楼-- · 2020-06-21 08:30

Another fancy code using && operator:

pid_t c1_pid, c2_pid;

(c1_pid = fork()) && (c2_pid = fork()); // Creates two children

if (c1_pid == 0) {
    /* Child 1 code goes here */
} else if (c2_pid == 0) {
    /* Child 2 code goes here */
} else {
    /* Parent code goes here */
}
查看更多
疯言疯语
3楼-- · 2020-06-21 08:31
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t AliceID, BobID;
double n=0;
int i1 =0;
/* fork a child process */
AliceID = fork();

if (AliceID < 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (AliceID == 0) { /* child Alice code */
    for(int i=1; i<11; i++)
          {n = n+i;
           i1++; }
        double avg1 = n/i1;
       printf("From Alice: the average of 1,2, …, 10 is the-average-she-calculated");
       printf("  sum = %.2f and avg = %.2f \n",n, avg1); 
     }
   else  { 
          BobID = fork();
         if (BobID == 0) { /* Child Bob code */
          printf("From Bob: I am born to print this and then die.\n");

        } else {  /* Parent Code */
                  /* parent will wait for the child to complete */
            wait(NULL);
            printf("From parent: AliceID is %d \n",  AliceID);
            printf("From parent: Bob is %d \n",  BobID);
            printf("Parent ID %d \n", getpid());

         }
}
return 0;
}
查看更多
登录 后发表回答