Fork without waiting

I'm not sure if I will do it right, I'm trying to create only 7 processes through ...

void err_sys(const char* x)
{
   perror(x);
   exit(1);
}


for(i = 1; i < 7; i++){
  switch(parent = fork()){
      case -1:
         err_sys("fork error");
      case 0:       //child
         printf("I'm the child, number %d(%d)\n", i, getpid());
         break;
      default:      //parent
         printf("I'm the parent(%d)\n", getpid());
         break;
  }
    if(parent)
       break;        //loop break
}

When I run it with prog | cat> file I get 6 exits from "I am a parent", followed by different numbers of children. However, there are 6 children with unique drinks. Other parent pids other than the first correspond to the child pid. Are these just some of the problems associated with quitting due to forking?

+4
source share
1 answer

; , . , " , , ", , , .

, 6 , , :

for (i = 1; i < 7; i++)

1, 2, 3, 4, 5, 6 . :

for (i = 0; i < 7; i++)      // Idiomatic C
for (i = 1; i <= 7; i++)     // Less idiomatic C

, err_sys() ( , break; ), :

  • . , err_sys().
  • ( parent 0), " ", .
  • ( parent ), " ", , .

. , , , .

-

, - . , . . , , ; , , ( - ). , , , , , , , , . 3 ..

fflush(0) fflush(stdout) ( switch, if) , . , .

+3

Source: https://habr.com/ru/post/1535208/


All Articles