~~Exercise.#~~
#include
#include
#include
int32_t doExpensiveComputation() { return 2 + 2; }
int main() {
int pfds[2];
pipe(pfds);
if (!fork()) {
int32_t result = doExpensiveComputation();
write(pfds[1], &result, 4);
return 0;
}
int32_t result;
read(pfds[0], &result, 4);
printf("The result is: %d\n", result);
return 0;
}
++++ The following version does a minimum of error checking. |
#include
#include
#include
int32_t doExpensiveComputation() { return 2 + 2; }
int main() {
int pfds[2];
if (pipe(pfds) == -1) {
perror("pipe");
return 1;
}
int f = fork();
if (f == -1) {
perror("fork");
return 1;
}
if (!f) {
int32_t result = doExpensiveComputation();
write(pfds[1], &result, 4);
return 0;
}
int32_t result;
read(pfds[0], &result, 4);
printf("The result is: %d\n", result);
return 0;
}
++++
~~Exercise.#~~
#include
#include
#include
#include
int32_t doExpensiveComputation() {
sleep(3);
return 2 + 2;
}
int main() {
int pfds[2];
pipe(pfds);
for (int i = 0; i < 3; ++i) {
if (!fork()) {
int32_t result = doExpensiveComputation();
write(pfds[1], &result, 4);
return 0;
}
}
int32_t result[4];
result[3] = doExpensiveComputation();
for (int i = 0; i < 3; ++i) {
read(pfds[0], result + i, 4);
wait(NULL);
}
printf("The result is: %d\n", result[0] + result[1] + result[2] + result[3]);
return 0;
}
~~Exercise.#~~
#include
#include
#include
int main() {
int pfds[2];
pipe(pfds);
if (!fork()) {
dup2(pfds[1], 1);
close(pfds[0]);
close(pfds[1]);
execlp("ls", "ls", "-l", NULL);
return 1;
}
close(pfds[1]);
char c;
while (1 == read(pfds[0], &c, 1)) {
c = toupper(c);
write(1, &c, 1);
}
return 0;
}
~~Exercise.#~~
#include
int main() {
int pfds[2];
pipe(pfds);
if (!fork()) {
dup2(pfds[1], 1);
close(pfds[0]);
close(pfds[1]);
execlp("ps", "ps", "-eF", NULL);
return 1;
}
dup2(pfds[0], 0);
close(pfds[0]);
close(pfds[1]);
execlp("sort", "sort", "-nk6", NULL);
return 1;
}
~~Exercise.#~~
#include
#include
#include
#include
void handleSignal(int num) {
write(2, "Shutting down...\n", 17);
exit(1);
}
int main() {
signal(SIGINT, handleSignal);
while (1)
getchar();
}
~~Exercise.#~~
#include
#include
#include
#include
#include
#include
void writeDateTo(int fd) {
struct timespec now;
char buf[21];
clock_gettime(CLOCK_REALTIME, &now);
buf[20] = '\n';
for (int i = 0; i < 10; ++i, now.tv_nsec /= 10)
buf[19 - i] = '0' + now.tv_nsec % 10;
buf[10] = '.';
for (int i = 0; i < 10; ++i, now.tv_sec /= 10)
buf[9 - i] = '0' + now.tv_sec % 10;
write(fd, buf, 21);
}
void handleSignal(int num) {
int fd = open("signal_log", O_WRONLY | O_APPEND | O_CREAT, 0666);
writeDateTo(fd);
close(fd);
}
int main() {
signal(SIGUSR1, handleSignal);
while (1)
getchar();
}
~~META:
language = en
~~