-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost.c
More file actions
104 lines (81 loc) · 2.6 KB
/
Copy pathhost.c
File metadata and controls
104 lines (81 loc) · 2.6 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#define DEBUG
/*
program.c ---> CGI program
Host.c ---> main program
In this example, Host will call the CGI program
and send the message ("Hello world") to CGI program,
then the CGI program will return the result to Host.
*/
int main(){
int cgiInput[2];
int cgiOutput[2];
int status;
char* inputData={"Hello world"};
pid_t cpid;
char c;
/* Use pipe to create a data channel betweeen two process
'cgiInput' handle data from 'host' to 'CGI'
'cgiOutput' handle data from 'CGI' to 'host'*/
if(pipe(cgiInput)<0){
perror("pipe");
exit(EXIT_FAILURE);
}
if(pipe(cgiOutput)<0){
perror("pipe");
exit(EXIT_FAILURE);
}
/* Creates a new process to execute cgi program */
if((cpid = fork()) < 0){
perror("fork");
exit(EXIT_FAILURE);
}
/*child process*/
if(cpid == 0){
printf("this is child process\n");
//close unused fd
close(cgiInput[1]);
close(cgiOutput[0]);
//redirect the output from stdout to cgiOutput
dup2(cgiOutput[1],STDOUT_FILENO);
//redirect the input from stdin to cgiInput
dup2(cgiInput[0], STDIN_FILENO);
//after redirect we don't need the old fd
close(cgiInput[0]);
close(cgiOutput[1]);
/* execute cgi program
the stdout of CGI program is redirect to cgiOutput
the stdin of CGI program is redirect to cgiInput
*/
execlp("./program.cgi","./program.cgi",NULL);
exit(0);
}
/*parent process*/
else{
printf("this is parent process\n");
//close unused fd
close(cgiOutput[1]);
close(cgiInput[0]);
// send the message to the CGI program
write(cgiInput[1], inputData, strlen(inputData));
// receive the message from the CGI program
while (read(cgiOutput[0], &c, 1) > 0){
// output the message to terminal
write(STDOUT_FILENO, &c, 1);
}
send(STDOUT_FILENO, "\n", 1, 0);
// connection finish
close(cgiOutput[0]);
close(cgiInput[1]);
waitpid(cpid, &status, 0);
}
}