Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pipe system call

Tags:

c

posix

ssh

pipe

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 reply. thanks in advance,..

like image 933
Prasanth Madhavan Avatar asked Nov 18 '25 22:11

Prasanth Madhavan


2 Answers

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.

like image 162
Fred Foo Avatar answered Nov 21 '25 17:11

Fred Foo


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).

like image 32
Nikolai Fetissov Avatar answered Nov 21 '25 18:11

Nikolai Fetissov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!