Pipe system call

can someone give me a simple example in c, use the pipe () system call and use ssh to connect to a remote server and execute a simple ls command and parse the response. thanks in advance,..

+3
source share
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 does not analyze the output from ls, since no program should do this. This is unreliable when file names contain spaces.

+5
source

pipe(2)creates a pair of file descriptors, one for reading, another for writing, which are related to each other. You can then fork(2)split your process into two and make them talk to each other through these descriptors.

"" , pipe(2).

+1

Source: https://habr.com/ru/post/1785212/


All Articles