pipe system call
can someone give me simple example in c, of using pipe() system call to and use ssh to connect to a remote server and execute a simple ls command and parse the开发者_Go百科 reply. thanks in advance,..
int main()
{
const char host[] = "foo.example.com"; // assume same username on remote
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: // child
close(fd[READ]);
if (dup2(fd[WRITE], STDOUT_FILENO) != -1)
execlp("ssh", "ssh", host, "ls", NULL);
_exit(1);
case -1: // error
perror("fork() failed");
return 1;
}
close(fd[WRITE]);
// write remote ls output to stdout;
while ((c = getc(childstdout)) != EOF)
putchar(c);
if (ferror(childstdout)) {
perror("I/O error");
return 1;
}
}
Note: the example doesn't parse the output from ls
, since no program should ever do that. It's unreliable when filenames contain whitespace.
pipe(2)
creates a pair of file descriptors, one for reading, the other for writing, that are connected to each other. Then you can fork(2)
to split your process into two and have them talk to each other via these descriptors.
You cannot "connect" to pre-existing process using pipe(2)
.
精彩评论