Fabietto206
13-04-2010, 14:53
Testo del progetto
Si scriva un programma C equivalente al comando di shell “cat /etc/passwd | grep ot > /tmp/foo 2>&1”, utilizzando le chiamate di sistema di Unix.
Ecco la mia soluzione:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
void fail(char *message) {
perror(message);
exit(1);
}
int main() {
int fd[2];
if (-1 == pipe(fd))
fail("pipe");
if (0 == fork()) {
close(0);
close(1);
if (0 != open("/etc/passwd", O_RDONLY))
fail("open passwd");
if (1 != dup(fd[1]))
fail("dup left");
close(fd[0]);
close(fd[1]);
execlp("cat", "cat", NULL);
fail("exec cat");
} else {
close(0);
close(2);
if (0 != dup(fd[0]))
fail("dup right");
if (2 != open("/tmp/foo", O_WRONLY | O_APPEND | O_CREAT, 0600))
fail("open foo");
close(fd[0]);
close(fd[1]);
execlp("grep", "grep", "-H", "root", NULL);
fail("exec grep");
}
return 0;
}
Si scriva un programma C equivalente al comando di shell “cat /etc/passwd | grep ot > /tmp/foo 2>&1”, utilizzando le chiamate di sistema di Unix.
Ecco la mia soluzione:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
void fail(char *message) {
perror(message);
exit(1);
}
int main() {
int fd[2];
if (-1 == pipe(fd))
fail("pipe");
if (0 == fork()) {
close(0);
close(1);
if (0 != open("/etc/passwd", O_RDONLY))
fail("open passwd");
if (1 != dup(fd[1]))
fail("dup left");
close(fd[0]);
close(fd[1]);
execlp("cat", "cat", NULL);
fail("exec cat");
} else {
close(0);
close(2);
if (0 != dup(fd[0]))
fail("dup right");
if (2 != open("/tmp/foo", O_WRONLY | O_APPEND | O_CREAT, 0600))
fail("open foo");
close(fd[0]);
close(fd[1]);
execlp("grep", "grep", "-H", "root", NULL);
fail("exec grep");
}
return 0;
}