Tôi đang cố gắng thực hiện bài tập về nhà mà tôi phải sử dụng fork()
nhưng tôi không biết tại sao tôi không thể dừng dĩa sau khi chạy chúng qua vòng lặp của tôi:fork() in for() loop
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
int limit = argc/2;
if(argc%2 == 0){
perror("the number of arguments given must pe even!");
exit(1);
}
int i;
for(i=0; i<=limit; i++){
if(fork()==-1){
perror("childes couldn't be created\n");
exit(1);
}
if(fork()==0){
printf("fork: %d \n",i);
exit(1);
}
wait(0);
}
printf("exiting...\n");
return 0;
}
Output:
[email protected]:~/OS/UprocH$ ./exe a b c d
fork: 0
fork: 0
fork: 1
fork: 1
fork: 1
fork: 2
fork: 2
fork: 1
fork: 2
exiting...
exiting...
fork: 2
exiting...
exiting...
fork: 2
exiting...
exiting...
exiting...
[email protected]:~/OS/UprocH$ fork: 2
fork: 2
fork: 2
exiting...
Bạn đang tìm kiếm hai lần trong cùng một vòng lặp, bạn có biết điều đó không? –
Noop làm thế nào đến, là ...? : < –
bạn đã tạo ra một quả bom ngã ba. Bạn nên làm một cái gì đó như: pid = fork(); if (pid <0) ...; if (pid == 0) .... – kofemann