管道系统调用

时间:2011-01-13 14:08:04

标签: c ssh posix pipe

有人可以在c中给我一个简单的例子,使用pipe()系统调用并使用ssh连接到远程服务器并执行一个简单的ls命令并解析回复。提前谢谢,..

2 个答案:

答案 0 :(得分:5)

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的输出,因为没有程序应该这样做。当文件名包含空格时,它是不可靠的。

答案 1 :(得分:1)

pipe(2)创建一对文件描述符,一个用于读取,另一个用于写入,彼此连接。然后你可以fork(2)将你的过程分成两部分,让他们通过这些描述符相互交谈。

您无法使用pipe(2)“连接”到预先存在的流程。

相关问题