File: channel_fork.c

package info (click to toggle)
tinyssh 20250501-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,388 kB
  • sloc: ansic: 20,245; sh: 1,582; python: 1,449; makefile: 913
file content (57 lines) | stat: -rw-r--r-- 1,190 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
20140129
20241209 - reformated using clang-format
Jan Mojzis
Public domain.
*/

#include <unistd.h>
#include "blocking.h"
#include "open.h"
#include "channel.h"

/*
The 'channel_fork' function is used to create a new process.
Function creates 3 pipes from/to child:
fd[0] is pipe to childs standard input
fd[1] is pipe from childs standard output
fd[2] is pipe from childs error output
Function returns also childs PID.
*/
long long channel_fork(int fd[3]) {

    int pi[2], pa[3], ch[3];
    long long i, pid;

    for (i = 0; i < 3; ++i) pa[i] = ch[i] = fd[i] = -1;
    for (i = 0; i < 3; ++i) {
        if (open_pipe(pi) == -1) goto cleanup;
        pa[i] = pi[i ? 0 : 1];
        ch[i] = pi[i ? 1 : 0];
    }

    pid = fork();
    if (pid == -1) goto cleanup;
    if (pid == 0) {
        for (i = 0; i < 3; ++i) {
            close(pa[i]);
            close(i);
            blocking_enable(ch[i]);
            if (dup(ch[i]) != i) _exit(111);
        }
        return 0;
    }
    for (i = 0; i < 3; ++i) {
        close(ch[i]);
        fd[i] = pa[i];
    }

    return pid;

cleanup:
    for (i = 0; i < 3; ++i) {
        close(pa[i]);
        close(ch[i]);
    }
    return -1;
}