3
可以有人给我简单的例子中C,使用配管()系统调用来的和使用ssh连接到远程服务器,并执行一个简单的ls命令和解析的答复。由于事先..管系统调用
可以有人给我简单的例子中C,使用配管()系统调用来的和使用ssh连接到远程服务器,并执行一个简单的ls命令和解析的答复。由于事先..管系统调用
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;
}
}
注意:该示例不分析ls
的输出,因为没有程序应该这样做。当文件名包含空白时,这是不可靠的。
您可能需要更新您对管道及SSH的问题。 – 2011-01-13 14:12:38
他们可能可以。但是这将是两个不同的例子 - 一个用于pipe(),另一个用于ssh()。 – 2011-01-13 14:19:00