回答編集履歴
3
winsock のコードのコメントの修正
answer
CHANGED
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
#pragma comment(lib, "ws2_32.lib")
|
|
45
45
|
|
|
46
46
|
#include <winsock2.h> // WSAStartup, WSACleanup, socket, closesocket, connect
|
|
47
|
-
#include <io.h> //
|
|
47
|
+
#include <io.h> // read, write
|
|
48
48
|
#include <stdio.h> // fprintf, perror
|
|
49
49
|
#include <stdlib.h> // exit
|
|
50
50
|
|
2
windows環境の説明を追加
answer
CHANGED
|
@@ -34,4 +34,59 @@
|
|
|
34
34
|
file2.txt の open を実行せずに int fd2 = 1; として標準出力にしたら
|
|
35
35
|
どうなりますか?
|
|
36
36
|
また、file1.txt の open を実行せずに int fd1 = 0; として標準入力にして、
|
|
37
|
-
キーボードから入力したりしてみてください。
|
|
37
|
+
キーボードから入力したりしてみてください。
|
|
38
|
+
### 追記
|
|
39
|
+
最初の質問の、参考にした「こちらの記事」は Unix環境での
|
|
40
|
+
ネットワークプログラミングです。
|
|
41
|
+
Windows では、そのままコンパイルできません。
|
|
42
|
+
次のような書き換えが必要でしょう。
|
|
43
|
+
```C
|
|
44
|
+
#pragma comment(lib, "ws2_32.lib")
|
|
45
|
+
|
|
46
|
+
#include <winsock2.h> // WSAStartup, WSACleanup, socket, closesocket, connect
|
|
47
|
+
#include <io.h> // socket
|
|
48
|
+
#include <stdio.h> // fprintf, perror
|
|
49
|
+
#include <stdlib.h> // exit
|
|
50
|
+
|
|
51
|
+
void send_input_data(int sockfd);
|
|
52
|
+
|
|
53
|
+
int main(int argc, char *argv[])
|
|
54
|
+
{
|
|
55
|
+
if (argc != 2) {
|
|
56
|
+
fprintf(stderr, "usage: %s machine-name\n", argv[0]); exit(1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
WSADATA wsaData = { 0 };
|
|
60
|
+
WSAStartup(MAKEWORD(2, 0), &wsaData);
|
|
61
|
+
|
|
62
|
+
SOCKET sockfd = socket(PF_INET, SOCK_STREAM, 0);
|
|
63
|
+
printf("sockfd = %x\n", sockfd);
|
|
64
|
+
if (sockfd == INVALID_SOCKET) { perror("client: socket"); exit(1); }
|
|
65
|
+
|
|
66
|
+
struct sockaddr_in client_addr = { 0 }; // bzero は使えない
|
|
67
|
+
client_addr.sin_family = PF_INET;
|
|
68
|
+
client_addr.sin_addr.s_addr = inet_addr(argv[1]);
|
|
69
|
+
client_addr.sin_port = htons(8000);
|
|
70
|
+
|
|
71
|
+
if (connect(sockfd, (struct sockaddr *) &client_addr, sizeof(client_addr)) > 0) {
|
|
72
|
+
perror("client: connect"); closesocket(sockfd); exit(1);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
send_input_data(sockfd);
|
|
76
|
+
|
|
77
|
+
closesocket(sockfd);
|
|
78
|
+
WSACleanup();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
void send_input_data(int sockfd)
|
|
82
|
+
{
|
|
83
|
+
char buf[128];
|
|
84
|
+
int buf_len;
|
|
85
|
+
while (1) {
|
|
86
|
+
buf_len = read(0, buf, 1);
|
|
87
|
+
write(sockfd, buf, buf_len);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
これはサーバマシンにデータを送信するクライアントアプリであり、
|
|
92
|
+
そのデータを受信するサーバアプリが別に必要です。
|
1
fd1, fd2 の表示の追加
answer
CHANGED
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
int fd2 = open("file2.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
|
|
16
16
|
if (fd2 < 0) { perror("write open"); return 2; }
|
|
17
17
|
|
|
18
|
+
printf("fd1 = %d, fd2 = %d\n", fd1, fd2);
|
|
19
|
+
|
|
18
20
|
char buf[N];
|
|
19
21
|
while (1) {
|
|
20
22
|
int n = read(fd1, buf, N);
|