Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
El proceso principal espera a que finalicen todos los procesos secundarios antes de continuar

Quiero que mi proceso principal espere a que finalicen todos los procesos secundarios antes de continuar, y tengo una solución.

 int status; pid_t pid = 0; int num = 0; for (int i = 0; i < NUMBER_OF_PROCESSES; i++) { pid = fork(); if (pid == 0) { //printf("Hello from Child\n"); sleep(5 - i); printf("Hello from Child %d\n",i + 1); num++; return 0; } else if (pid) { waitpid(pid, &status, 0); continue; } else { printf("Error\n"); exit(1); } } printf("Hello from the process, currentPid : %d, pid : %d\n", getpid(), pid); return 0;

Pero parece que tengo que esperar cada proceso secundario antes de que finalice, ¿hay alguna forma de que todos los procesos secundarios puedan ejecutarse en paralelo?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede iniciar a todos sus hijos (y retener su pid), y luego, usará waitpid (vea la opción para esperar a cualquier hijo) en un ciclo hasta que no quede ningún hijo.

¿Te suena bien?

Editar :

 #define NB_PROCESSES 5 int main(void) { pid_t pidChild[NB_PROCESSES]; pid_t stoppedChild; int nbChild = 0; printf("Launching all child.\n"); for (int i = 0; i < NB_PROCESSES; ++i) { if ((pidChild[i] = fork()) == -1) { printf("Error while fork the %d child : errno = '%s'.\n", i, strerror(errno)); } else { if (pidChild[i] == 0) { sleep(NB_PROCESSES - i); printf("Hello from Child %d\n",i); return (0); } else { ++nbChild; } } } printf("Waiting all child.\n"); while (nbChild) { stoppedChild = waitpid(WAIT_ANY, NULL, 0); for (int i = 0; i < NB_PROCESSES; ++i) { if (stoppedChild == pidChild[i]) { printf("Child %d stopped.\n", i); } } --nbChild; } printf("Hello from the process, currentPid : %d\n", getpid()); return (0); }

Puedes retener su pid así.

over 4 years ago · Santiago Trujillo Report

0

Solo tiene que iniciar los procesos en un bucle y luego, en el proceso original, esperar hasta que no haya más niños vivos. Me gusta esto:

 for (int i = 0; i < NUMBER_OF_PROCESSES; i++) { pid = fork(); if (pid == 0) { // child sleep(5 - i); printf("Hello from Child %d\n",i + 1); num++; return 0; } else if (pid==-1) { printf("Error\n"); break; // out on failure } } // try to wait for any children while there exists at least one while ((pid=waitpid(-1,&status,0))!=-1) { printf("Process %d terminated\n",pid); }

Entonces los niños vivirán concurrentemente y el padre esperará su terminación.

over 4 years ago · Santiago Trujillo Report

0

Usar waitpid

 waitpid(childPid, &returnStatus, 0); // Parent process waits here for child to terminate. if (returnStatus == 0) // Verify child process terminated without error. { std::cout << "The child process terminated normally." << std::endl; } if (returnStatus == 1) { std::cout << "The child process terminated with an error!." << std::endl; }

Procesos secundarios en paralelo. Es posible que un elemento secundario se ejecute rápidamente y finalice antes de que se ejecuten las siguientes, en cuyo caso los elementos secundarios se ejecutan en serie.

 for( int n = 0; n < 4; ++n ) { switch( fork()) { /* do stuff, but don't wait() or terminate */ } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!