Repository navigation
Expand file tree
/
Copy pathserver_py.c
More file actions
106 lines (87 loc) · 2.3 KB
/
Copy pathserver_py.c
File metadata and controls
106 lines (87 loc) · 2.3 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
105
106
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define SERVER_PORT 5000
#define BUFLEN 300
#define FILENAME "upload.img"
#define PYTHONCMD "python simplep.py"
void eventhandler() {
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[]){
int sock, clientsock;
struct sockaddr_in cliAddr,srvAddr;
//register signal event
signal(SIGINT, eventhandler);
/*create socket*/
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("fail to create a socket");
exit(EXIT_FAILURE);
}
srvAddr.sin_family = AF_INET;
srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
srvAddr.sin_port = htons(SERVER_PORT);
//bind server address
if(bind(sock, (struct sockaddr *)&srvAddr, sizeof(srvAddr)) < 0 ) {
perror("fail to address");
exit(EXIT_FAILURE);
}
listen(sock, 50);
while(1) {
//start to read data from clients
printf("%s: start to wait connetions from client on TCP port %u\n", argv[0] , SERVER_PORT);
int clilen;
int status,pid;
clilen = sizeof(cliAddr);
clientsock = accept( sock, (struct sockaddr *)&cliAddr, &clilen);
printf("A client connected.\n");
if(clientsock < 0) {
perror("fail to address");
exit(EXIT_FAILURE);
}
//fork a child process to do the task; parent will accept another connection.
if( (pid=fork()) == 0) {
//read data
int n;
char buf[BUFLEN];
unlink(FILENAME);
FILE *fp;
fp = fopen(FILENAME, "w+");
printf("receiving image data.\n");
while( (n = recv(clientsock, buf, BUFLEN, 0)) > 0 ) {
//write(STDOUT_FILENO, buf, n);
//printf("\33[2k\r finished %d percent.", 20);
printf(".");
fwrite(buf, 1, n, fp);
}
fclose(fp);
if(n < 0) perror("recv error\n");
printf("finished!\n");
//execute python
FILE *cmdpipe;
char stdoutbuff[1035];
cmdpipe = popen( PYTHONCMD, "r" );
if(cmdpipe == NULL) {
printf("Failed to run python command.\n");
exit(EXIT_FAILURE);
}
while (fgets(stdoutbuff, sizeof(stdoutbuff)-1, cmdpipe)) {
printf("%s\n",stdoutbuff);
}
pclose(fp);
//close socket
close(clientsock);
exit(EXIT_SUCCESS);
}
//parent process.
//waitpid( pid, &status, WNOHANG);
waitpid( -1, &status, WNOHANG); //wait for any child
}
}