#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main(int argc, char ** argv)
{
int pid;
int status;
pid = fork();
if (pid < 0)
{
printf("Cannot create a child process");
exit(1);
}
else if (pid == 0)
{
printf("I am the child process. %d \n", getpid());
printf("The child process is done. \n");
fflush(stdout); // it does not write immediately to a disk.
exit(0);
}
else
{
printf("I am the parent process.%d \n", getpid());
sleep(5); // sleep does not works
pid = wait(&status); // want to wait until the child is complited
printf("The parent process is done. \n");
fflush(stdout); // it does not write immediately to a disk.
exit(1);
}
}
Hallo Leute, ich versuche derzeit, einen Kindprozess zu erstellen. So weit, so gut, was ich jetzt versuche, ist, das Kind zuerst auszuführen und auszudrucken und immer die Nachricht "Der Elternprozess ist fertig" auszudrucken.Ausführen von Kind vor dem Eltern in C
I am the parent process.28847
I am the child process. 28848
The child process is done.
The parent process is done.
Derzeit druckt diese:
I am the parent process.28847
The parent process is done.
I am the child process. 28848
The child process is done.
Es ist mein erstes Mal Forking mit so bin ich nicht wirklich sicher, was ich tue, ich habe versucht, schlafen und warten (& Status) zu versuchen Sie zu warten, bis der Kindprozess beendet ist, und führen Sie dann den Elternprozess aus, aber etwas funktioniert nicht.
P.S. Entschuldigung für das schlechte Layout, zum ersten Mal mit stackoverflow.
Sie sollten wahrscheinlich verwenden [ 'wait()'] (http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html) oder ['waitpid()'] (http://pubs.opengroup.org/onlinepubs/9699919799/functions/waitpid.html). –
In Ihrem Code wird "Der Elternprozess ist fertig" immer als letztes gedruckt (da Sie 'wait()' verwenden). – usr
Vielen Dank, ich habe es geschafft, es zu beheben. Ich werde Mutex und Semaphore überprüfen und wie kann ich es verbessern. –