Wettrennen Prozesse



  • Hi Leute, ich möchte gerne feststellen ob der Kindprozess oder der Elternprozess als erstes fertig ist mit zählen.
    Irgendwie kommt es immer zur Ausgabe, dass der Vaterprozess Erster ist, auch wenn das nicht der Fall ist.
    Schätze das irgendwas mit den waitpid-rufen nicht stimmt. Kann mir jemand helfe 😕

    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <sys/wait.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
    	long int zahl = 1;
    	pid_t pid;
    
    	printf("Eltern- und Kindprozess zaehlen um die Wette:\n\n");
    
    	if((pid=fork()) < 0)
    	{
    		perror("Konnte Prozess nicht erstellen.");
    		return EXIT_FAILURE;
    	}
    
    	else if(pid == 0)
    	{		
    		while(zahl <= 10000000)
    		{
    			if((zahl % 2000000) == 0)
    			{
    				printf("%65s %ld\n", "Kind:", zahl);
    				usleep(1);
    			}
    			zahl++;
    		}
    	}
    
    	else if(pid > 0)
    	{		
    		while(zahl <= 10000000)
    		{
    			if((zahl % 2000000) == 0)
    			{
    				printf("Vater: %ld\n", zahl);
    				usleep(1);
    			}
    			zahl++;			
    		}
    
    		if(waitpid(pid, NULL, WNOHANG) == 0)
    		{
    			printf("Vaterprozess hat gewonnen!\n");
    		}
    
    		else if(waitpid(pid, NULL, WNOHANG) > 0)
    		{
    			printf("Kindprozess hat gewonnen!\n");
    		}		
    	}	
    
    	sleep(1);
    
    	return EXIT_SUCCESS;
    }
    


  • Ich idiot, wenn ich den Rückgabewert vom ersten waitpid-ruf speichere und beim zweiten vergleich einsetze, funktioniert alles wie gewollt. 😃
    Und den Kindprozess hab ich vorher natürlich noch mit exit beendet.


Anmelden zum Antworten