File: channel_forktest.c

package info (click to toggle)
tinyssh 20230101-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,244 kB
  • sloc: ansic: 12,106; sh: 1,168; python: 479; makefile: 42
file content (79 lines) | stat: -rw-r--r-- 2,117 bytes parent folder | download | duplicates (4)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
20140416
Jan Mojzis
Public domain.
*/

#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include "fail.h"
#include "writeall.h"
#include "readall.h"
#include "byte.h"
#include "channel.h"


/* test if channel_fork pipes works from child to parent */
static void test1(void) {

    int fd[3];
    pid_t pid;
    int status;
    char buf[5];

    pid = channel_fork(fd);
    if (pid == -1) fail("channel_fork failure");
    if (pid == 0) {
        if (writeall(1, "ahoj1", 5) == -1) fail("writeall failure");
        if (writeall(2, "ahoj2", 5) == -1) fail("writeall failure");
        _exit(0);
    }
    if (fd[0] == -1) fail("channel_fork failure");
    if (fd[1] == -1) fail("channel_fork failure");
    if (fd[2] == -1) fail("channel_fork failure");

    if (readall(fd[1], buf, 5) == -1) fail("readall failure");
    if (!byte_isequal(buf, 5, "ahoj1")) fail("readall failure");
    if (readall(fd[2], buf, 5) == -1) fail("readall failure");
    if (!byte_isequal(buf, 5, "ahoj2")) fail("readall failure");

    while (waitpid(pid, &status, 0) != pid) {};
    if (!WIFEXITED(status)) fail("process killed");
    if (WEXITSTATUS(status)) fail("process exited with status != 0");
}

/* test if channel_fork pipes works from parent to child */
static void test2(void) {

    int fd[3];
    pid_t pid;
    int status;
    char buf[5];

    pid = channel_fork(fd);
    if (pid == -1) fail("channel_fork failure");
    if (pid == 0) {
        if (readall(0, buf, 5) == -1) fail("readall failure");
        if (!byte_isequal(buf, 5, "ahoj0")) fail("readall failure");
        _exit(0);
    }
    if (fd[0] == -1) fail("channel_fork failure");
    if (fd[1] == -1) fail("channel_fork failure");
    if (fd[2] == -1) fail("channel_fork failure");

    if (writeall(fd[0], "ahoj0", 5) == -1) fail("writeall failure");

    while (waitpid(pid, &status, 0) != pid) {};
    if (!WIFEXITED(status)) fail("process killed");
    if (WEXITSTATUS(status)) fail("process exited with status != 0");
}

int main(void) {
    alarm(10);
    test1();
    test2();
    _exit(0);
}