Ich habe folgenden C Code:
Eine Ausgabe auf die Konsole sieht so aus:
p
p
c
p
p
c
p
c
p
c
c
c
c
c
Eine in die Datei so:
c
c
c
c
c
c
c
c
p
p
p
p
p
p
Da kommt mir doch glatt die Frage, warum das in der Datei sortiert ist und auf der Konsole nicht. Kann mir das mal jemand erklären?
Code:
/*
* OS Praktikum 1
* a4.c created on 26.03.2007
* by moritz
*/
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/procfs.h>
#include "error.h"
int main(int argc, char* argv[]) {
FILE *file;
char *datei="ausgabe";
file = fopen(datei,"w");
int child, i, sleep_parent, sleep_child, tofile=0;
if(argc <3) {
printf("sleeptime for parent: ");
scanf("%d", &sleep_parent);
printf("sleeptime for child: ");
scanf("%d", &sleep_child);
}
else {
sleep_parent = atoi(argv[1]);
sleep_child = atoi(argv[2]);
}
if(sleep_parent < 0 || sleep_child < 0)
error_exit("negative time... nice try!",4706);
child = fork(); // create a child and return its PID
/* ab hier läuft der Code quasi 2mal!
* einmal als Child und einmal als Parent
*/
if(child < 0)
error_exit("error while creating a child",4707);
/* wenn ich child bin, dann bin ich fuer mich 0
* -> diese Schleife startet
*/
if(child == 0) {
for(i=0;i<=7;i++) {
sleep((uint)sleep_child);
if(tofile == 0)
printf("c\n");
else
fprintf(file,"c\n");
}
exit(0);
}
/* bin ich parent, ist child nicht 0, sondern die PID (Rückgabe von fork();!)
* -> diese Schleife läuft
*/
else {
for(i=0;i<=5;i++) {
if(tofile == 0)
printf("p\n");
else
fprintf(file,"p\n");
sleep((uint)sleep_parent);
}
/* parent wartet auf child, ansonsten kommt auf der Konsole eine Ausgabe
* obwohl man schon weitere Befehle eingeben kann!
*/
waitpid(child,NULL,0);
}
return 0;
}
p
p
c
p
p
c
p
c
p
c
c
c
c
c
Eine in die Datei so:
c
c
c
c
c
c
c
c
p
p
p
p
p
p
Da kommt mir doch glatt die Frage, warum das in der Datei sortiert ist und auf der Konsole nicht. Kann mir das mal jemand erklären?
Übrigens ist es unabhängig von irgendwelchen Werten!