int main()
{
const char host[] = "foo.example.com";
enum { READ = 0, WRITE = 1 };
int c, fd[2];
FILE *childstdout;
if (pipe(fd) == -1
|| (childstdout = fdopen(fd[READ], "r")) == NULL) {
perror("pipe() or fdopen() failed");
return 1;
}
switch (fork()) {
case 0:
close(fd[READ]);
if (dup2(fd[WRITE], STDOUT_FILENO) != -1)
execlp("ssh", "ssh", host, "ls", NULL);
_exit(1);
case -1:
perror("fork() failed");
return 1;
}
close(fd[WRITE]);
while ((c = getc(childstdout)) != EOF)
putchar(c);
if (ferror(childstdout)) {
perror("I/O error");
return 1;
}
}
Note. The example does not analyze the output from ls, since no program should do this. This is unreliable when file names contain spaces.
source
share