Zurück zur SPiC Übersicht
pwc.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
static void die(const char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
static unsigned int wordcount(const char *file) {
FILE *fp = fopen(file, "r");
if (fp == NULL) {
die(file);
}
unsigned int words = 0;
int trennzeichen = 1;
while (1) {
int c = fgetc(fp);
if (c == EOF) {
if (trennzeichen == 0) { words++;
}
break;
}
if (c == ' ' || c == '\n' || c == '\t') {
if (trennzeichen == 0) {
trennzeichen = 1;
words++;
}
} else {
trennzeichen = 0;
}
}
if (ferror(fp)) {
die(file);
}
fclose(fp);
return words;
}
int main(int argc, char *argv[]) {
if (argc == 1) {
fprintf(stderr, "Syntax: %s <file...>\n", argv[0]);
exit(EXIT_FAILURE);
}
for (int i = 1; i < argc; i++) {
pid_t pid = fork();
if (pid == -1) {
die("fork");
}
if (pid == 0) {
unsigned int wc = wordcount(argv[i]);
printf("%s: %u\n", argv[i], wc);
exit(EXIT_SUCCESS);
}
}
int ok = 1;
for (int i = 1; i < argc; i++) {
int status = 0;
pid_t p = wait(&status);
if (p < 0) {
die("wait");
}
if (WIFEXITED(status) && WEXITSTATUS(status) != EXIT_SUCCESS) {
ok = 0;
}
}
if (ok == 0) {
fprintf(stderr, "Fehler!\n");
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}