├── .gitignore
├── CONTRIBUTORS.md
├── LICENSE
├── README.md
├── fs
├── 1.mmap_write_performance
│ ├── Makefile
│ ├── README.txt
│ └── mmap_write_performance.c
├── 2.mmap_read_performance
│ ├── Makefile
│ ├── README.txt
│ └── mmap_read_performance.c
├── 3.mmap_write_sync_nocache
│ ├── Makefile
│ └── mmap_write_sync_nocache.c
├── 4.mmap_read_sync_nocache
│ ├── Makefile
│ └── mmap_read_sync_nocache.c
├── 5.multi_thread_write_file
│ ├── Makefile
│ └── multi_thread_write_file.c
└── README.md
├── ipc
├── 1.mkfifo_with_unblock
│ ├── Makefile
│ └── mkfifo_with_nonblock.c
├── 2.unix_sock_recv_peer
│ ├── Makefile
│ └── unix_sock_recv_peer.c
└── README.md
├── kernel
├── 1.rwlock_spinlock_performance
│ ├── Makefile
│ └── lock_test.c
├── 2.sleep_test
│ ├── Makefile
│ └── sleep_test.c
└── README.md
├── mem
├── 1.vsz_and_rss
│ ├── Makefile
│ └── vsz_and_rss.cpp
└── README.md
├── networks
├── 1.tcp_close_with_data
│ ├── Makefile
│ ├── README.md
│ └── tcp_close_with_data.c
├── 10.udp_listen_unexpected_port
│ ├── Makefile
│ └── udp_listen_unexpected_port.c
├── 2.tcp_push_packet
│ ├── Makefile
│ ├── README.md
│ └── tcp_force_push.c
├── 3.tcp_unread_hit_rst
│ ├── Makefile
│ ├── README.md
│ └── tcp_unread_rst.c
├── 4.reuse_addr_option
│ ├── Makefile
│ └── reuse_addr_option.c
├── 5.no_listen_tcp_conn
│ ├── Makefile
│ └── no_listen_tcp_conn.c
├── 6.tcp_keepalive_reporter
│ ├── Makefile
│ └── tcp_keepalive_report.c
├── 7.tcp_send_rst
│ ├── Makefile
│ └── tcp_send_rst.c
├── 8.connect_until_fail
│ ├── accpet_util_fail.py
│ └── connect_until_fail.py
├── 9.tcp_unread_shutdown
│ ├── Makefile
│ ├── README.md
│ └── tcp_unread_shutdown.c
└── README.md
├── process
├── 1.child_inherit_flock
│ ├── Makefile
│ ├── README.md
│ └── child_inherit_flock.c
├── 2.child_share_flock
│ ├── Makefile
│ ├── README.md
│ └── child_share_flock.c
├── 3.fork_and_print
│ ├── Makefile
│ ├── README.md
│ └── fork_and_print.c
├── 4.fork_with_fd
│ ├── Makefile
│ ├── README.md
│ └── fork_with_fd.c
└── README.md
└── signal
├── 1.waitpid_sigchld_ignore
├── Makefile
├── README.md
└── waitpid_sigchld_ignore.c
├── 2.waitanypid_sigchld_ignore
├── Makefile
├── README.md
└── waitanypid_sigchld_ignore.c
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | # Object files
2 | *.o
3 | *.ko
4 | *.obj
5 | *.elf
6 |
7 | # Precompiled Headers
8 | *.gch
9 | *.pch
10 |
11 | # Libraries
12 | *.lib
13 | *.a
14 | *.la
15 | *.lo
16 |
17 | # Shared objects (inc. Windows DLLs)
18 | *.dll
19 | *.so
20 | *.so.*
21 | *.dylib
22 |
23 | # Executables
24 | *.exe
25 | *.out
26 | *.app
27 | *.i*86
28 | *.x86_64
29 | *.hex
30 |
31 | # Debug files
32 | *.dSYM/
33 | *.su
34 |
35 | # Tmp files
36 | *.txt
37 | *.d
38 | *.ko*
39 | *.cmd
40 |
41 |
--------------------------------------------------------------------------------
/CONTRIBUTORS.md:
--------------------------------------------------------------------------------
1 | This file contains a list of people who made some contribution.
2 |
3 |
4 | # Share the codes and knowledge
5 |
6 |
7 | gfree.wind@gmail.com: The founder and maintainer
8 |
9 |
10 | # Raise the problem
11 |
12 | ly(2270597823@qq.com): Close the TCP socket with pending data
13 |
14 |
15 |
16 | ## Note
17 |
18 |
19 | Welcome every to join QQ group 4367710!
20 | Share your knowledges or raise one problem.
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 简介
2 |
3 | 这个工程是用于研究Linux环境编程的一些细节。
4 | 其中每个目录聚焦于一个主题,每个主题目录下面,每个问题又有自己的单独目录。
5 |
6 | 因为这些是测试代码,所以没有细致的进行错误处理。就直接退出进程了事:))
7 | 后面为了方便,干脆都没有检查函数的返回值:))在工作中,可不能这样哦~~~
8 |
9 | 每一个子目录都验证Linux编程的一个问题。
10 | 要了解细节的话,可以进入具体的目录得到详细的解答。
11 |
12 | 每个目录下面都有一个README.md文件,用于介绍该目录或者分析具体的问题。
13 |
14 | # General
15 | This project is used to investigate on the details of Linux programming.
16 | Every directory focuses on one topic.
17 | Every topic dir contains different dir which investigates on different problems.
18 |
19 | Becasue they are test codes, so I don't perform the delicated error handler.
20 | Just exit the process :))
21 | I don't check the return value of function in the latter codes.
22 | But you could not do it in real product:))
23 |
24 | Every directory focuses on one Linux topic. For example, the signal dir focuses
25 | on the signal details of Linux Programming.
26 |
27 | There is one README.md file in every directory. It is used to introduce the dir
28 | or analyze the details of one problem.
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/fs/1.mmap_write_performance/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -Werror -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := mmap_write_performance
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/fs/1.mmap_write_performance/README.txt:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | Firstly, we use mmap to write one file with 1024, 2048, 4096,
4 | and 5120 bytes for 1000000 times.
5 | Then we write another file with 1024, 2048, 4096 and 5120 bytes
6 | for 1000000 times too.
7 |
8 | # Conclusion
9 |
10 | The performane of mmap write is worser than direct write.
11 |
12 |
13 |
--------------------------------------------------------------------------------
/fs/1.mmap_write_performance/mmap_write_performance.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: mmap_write_performance.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 10/06/2016 12:20:48 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng (gfree.wind@gmail.com)
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 |
19 | #include
20 | #include
21 |
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 |
31 | #define TEST_LOOPS (1000000)
32 |
33 | int main(void)
34 | {
35 | int cost, i, fd;
36 | time_t start, end;
37 | char buf[5120] = {"Hello world!\n"};
38 |
39 | start = time(NULL);
40 | fd = open("./mmap_write.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
41 | ftruncate(fd, 1024);
42 | for (i = 0; i < TEST_LOOPS; ++i) {
43 | char *addr = mmap(NULL, 1024, PROT_WRITE, MAP_SHARED, fd, 0);
44 | memcpy(addr, buf, 1024);
45 | munmap(addr, 1024);
46 | }
47 | close(fd);
48 | end = time(NULL);
49 | cost = end - start;
50 | printf("mmap write 1024 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
51 |
52 | start = time(NULL);
53 | fd = open("./mmap_write.txt", O_CREAT|O_RDWR|O_TRUNC);
54 | ftruncate(fd, 2048);
55 | for (i = 0; i < TEST_LOOPS; ++i) {
56 | char *addr = mmap(NULL, 2048, PROT_WRITE, MAP_SHARED, fd, 0);
57 | memcpy(addr, buf, 2048);
58 | munmap(addr, 2048);
59 | }
60 | close(fd);
61 | end = time(NULL);
62 | cost = end - start;
63 | printf("mmap write 2048 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
64 |
65 | start = time(NULL);
66 | fd = open("./mmap_write.txt", O_CREAT|O_RDWR|O_TRUNC);
67 | ftruncate(fd, 4096);
68 | for (i = 0; i < TEST_LOOPS; ++i) {
69 | char *addr = mmap(NULL, 4096, PROT_WRITE, MAP_SHARED, fd, 0);
70 | memcpy(addr, buf, 4096);
71 | munmap(addr, 4096);
72 | }
73 | close(fd);
74 | end = time(NULL);
75 | cost = end - start;
76 | printf("mmap write 4096 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
77 |
78 | start = time(NULL);
79 | fd = open("./mmap_write.txt", O_CREAT|O_RDWR|O_TRUNC);
80 | ftruncate(fd, 5120);
81 | for (i = 0; i < TEST_LOOPS; ++i) {
82 | char *addr = mmap(NULL, 5120, PROT_WRITE, MAP_SHARED, fd, 0);
83 | memcpy(addr, buf, 5120);
84 | munmap(addr, 5120);
85 | }
86 | close(fd);
87 | end = time(NULL);
88 | cost = end - start;
89 | printf("mmap write 5120 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
90 |
91 |
92 | start = time(NULL);
93 | fd = open("./direct_write.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
94 | for (i = 0; i < TEST_LOOPS; ++i) {
95 | pwrite(fd, buf, 1024, 0);
96 | }
97 | close(fd);
98 | end = time(NULL);
99 | cost = end - start;
100 | printf("direct write 1024 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
101 |
102 | start = time(NULL);
103 | fd = open("./direct_write.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
104 | for (i = 0; i < TEST_LOOPS; ++i) {
105 | pwrite(fd, buf, 2048, 0);
106 | }
107 | close(fd);
108 | end = time(NULL);
109 | cost = end - start;
110 | printf("direct write 2048 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
111 |
112 | start = time(NULL);
113 | fd = open("./direct_write.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
114 | for (i = 0; i < TEST_LOOPS; ++i) {
115 | pwrite(fd, buf, 4096, 0);
116 | }
117 | close(fd);
118 | end = time(NULL);
119 | cost = end - start;
120 | printf("direct write 4096 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
121 |
122 | start = time(NULL);
123 | fd = open("./direct_write.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
124 | for (i = 0; i < TEST_LOOPS; ++i) {
125 | pwrite(fd, buf, 5120, 0);
126 | }
127 | close(fd);
128 | end = time(NULL);
129 | cost = end - start;
130 | printf("direct write 5120 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
131 |
132 |
133 |
134 | return 0;
135 | }
136 |
137 |
--------------------------------------------------------------------------------
/fs/2.mmap_read_performance/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -Werror -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := mmap_read_performance
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/fs/2.mmap_read_performance/README.txt:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | Firstly, we use mmap to read one file with 1024, 2048, 4096,
4 | and 5120 bytes for 1000000 times.
5 | Then we read another file with 1024, 2048, 4096 and 5120 bytes
6 | for 1000000 times too.
7 |
8 | # Conclusion
9 |
10 | The performane of mmap read is worser than direct read.
11 |
12 |
13 |
--------------------------------------------------------------------------------
/fs/2.mmap_read_performance/mmap_read_performance.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: mmap_write_performance.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 10/06/2016 12:20:48 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng (gfree.wind@gmail.com)
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 |
19 | #include
20 | #include
21 |
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 |
31 | #define TEST_LOOPS (1000000)
32 |
33 | int main(void)
34 | {
35 | int cost, i, fd;
36 | time_t start, end;
37 | char buf[5120];
38 |
39 | start = time(NULL);
40 | fd = open("./mmap_read.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
41 | ftruncate(fd, 1024);
42 | for (i = 0; i < TEST_LOOPS; ++i) {
43 | char *addr = mmap(NULL, 1024, PROT_READ, MAP_SHARED, fd, 0);
44 | memcpy(buf, addr, 1024);
45 | munmap(addr, 1024);
46 | }
47 | close(fd);
48 | end = time(NULL);
49 | cost = end - start;
50 | printf("mmap read 1024 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
51 |
52 | start = time(NULL);
53 | fd = open("./mmap_read.txt", O_CREAT|O_RDWR|O_TRUNC);
54 | ftruncate(fd, 2048);
55 | for (i = 0; i < TEST_LOOPS; ++i) {
56 | char *addr = mmap(NULL, 2048, PROT_READ, MAP_SHARED, fd, 0);
57 | memcpy(buf, addr, 2048);
58 | munmap(addr, 2048);
59 | }
60 | close(fd);
61 | end = time(NULL);
62 | cost = end - start;
63 | printf("mmap read 2048 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
64 |
65 | start = time(NULL);
66 | fd = open("./mmap_read.txt", O_CREAT|O_RDWR|O_TRUNC);
67 | ftruncate(fd, 4096);
68 | for (i = 0; i < TEST_LOOPS; ++i) {
69 | char *addr = mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0);
70 | memcpy(buf, addr, 4096);
71 | munmap(addr, 4096);
72 | }
73 | close(fd);
74 | end = time(NULL);
75 | cost = end - start;
76 | printf("mmap read 4096 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
77 |
78 | start = time(NULL);
79 | fd = open("./mmap_read.txt", O_CREAT|O_RDWR|O_TRUNC);
80 | ftruncate(fd, 5120);
81 | for (i = 0; i < TEST_LOOPS; ++i) {
82 | char *addr = mmap(NULL, 5120, PROT_READ, MAP_SHARED, fd, 0);
83 | memcpy(buf, addr, 5120);
84 | munmap(addr, 5120);
85 | }
86 | close(fd);
87 | end = time(NULL);
88 | cost = end - start;
89 | printf("mmap read 5120 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
90 |
91 |
92 | start = time(NULL);
93 | fd = open("./direct_read.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
94 | ftruncate(fd, 1024);
95 | for (i = 0; i < TEST_LOOPS; ++i) {
96 | pread(fd, buf, 1024, 0);
97 | }
98 | close(fd);
99 | end = time(NULL);
100 | cost = end - start;
101 | printf("direct read 1024 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
102 |
103 | start = time(NULL);
104 | fd = open("./direct_read.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
105 | ftruncate(fd, 2048);
106 | for (i = 0; i < TEST_LOOPS; ++i) {
107 | pread(fd, buf, 2048, 0);
108 | }
109 | close(fd);
110 | end = time(NULL);
111 | cost = end - start;
112 | printf("direct read 2048 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
113 |
114 | start = time(NULL);
115 | fd = open("./direct_read.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
116 | ftruncate(fd, 4096);
117 | for (i = 0; i < TEST_LOOPS; ++i) {
118 | pread(fd, buf, 4096, 0);
119 | }
120 | close(fd);
121 | end = time(NULL);
122 | cost = end - start;
123 | printf("direct read 4096 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
124 |
125 | start = time(NULL);
126 | fd = open("./direct_read.txt", O_CREAT|O_RDWR|O_TRUNC, 0644);
127 | ftruncate(fd, 5120);
128 | for (i = 0; i < TEST_LOOPS; ++i) {
129 | pread(fd, buf, 5120, 0);
130 | }
131 | close(fd);
132 | end = time(NULL);
133 | cost = end - start;
134 | printf("direct read 5120 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
135 |
136 |
137 | return 0;
138 | }
139 |
140 |
--------------------------------------------------------------------------------
/fs/3.mmap_write_sync_nocache/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -Werror -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := mmap_write_sync_nocache
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/fs/3.mmap_write_sync_nocache/mmap_write_sync_nocache.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: mmap_write_performance.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 10/06/2016 12:20:48 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng (gfree.wind@gmail.com)
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 |
19 | #define _GNU_SOURCE
20 |
21 | #include
22 | #include
23 |
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 |
33 | #define TEST_LOOPS (10000000)
34 |
35 | int main(void)
36 | {
37 | int cost, i, fd;
38 | time_t start, end;
39 | char buf[20480] = {"Hello world!\n"};
40 |
41 | start = time(NULL);
42 | fd = open("./mmap_write.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC, 0644);
43 | ftruncate(fd, 4096);
44 | for (i = 0; i < TEST_LOOPS; ++i) {
45 | char *addr = mmap(NULL, 4096, PROT_WRITE, MAP_SHARED, fd, 0);
46 | memcpy(addr, buf, 4096);
47 | munmap(addr, 4096);
48 | }
49 | close(fd);
50 | end = time(NULL);
51 | cost = end - start;
52 | printf("mmap write 4096 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
53 |
54 | start = time(NULL);
55 | fd = open("./mmap_write.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC);
56 | ftruncate(fd, 8192);
57 | for (i = 0; i < TEST_LOOPS; ++i) {
58 | char *addr = mmap(NULL, 8192, PROT_WRITE, MAP_SHARED, fd, 0);
59 | memcpy(addr, buf, 8192);
60 | munmap(addr, 8192);
61 | }
62 | close(fd);
63 | end = time(NULL);
64 | cost = end - start;
65 | printf("mmap write 8192 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
66 |
67 | start = time(NULL);
68 | fd = open("./mmap_write.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC);
69 | ftruncate(fd, 12288);
70 | for (i = 0; i < TEST_LOOPS; ++i) {
71 | char *addr = mmap(NULL, 12288, PROT_WRITE, MAP_SHARED, fd, 0);
72 | memcpy(addr, buf, 12288);
73 | munmap(addr, 12288);
74 | }
75 | close(fd);
76 | end = time(NULL);
77 | cost = end - start;
78 | printf("mmap write 12288 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
79 |
80 |
81 | start = time(NULL);
82 | fd = open("./direct_write.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC, 0644);
83 | for (i = 0; i < TEST_LOOPS; ++i) {
84 | pwrite(fd, buf, 4096, 0);
85 | }
86 | close(fd);
87 | end = time(NULL);
88 | cost = end - start;
89 | printf("direct write 4096 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
90 |
91 | start = time(NULL);
92 | fd = open("./direct_write.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC, 0644);
93 | for (i = 0; i < TEST_LOOPS; ++i) {
94 | pwrite(fd, buf, 8192, 0);
95 | }
96 | close(fd);
97 | end = time(NULL);
98 | cost = end - start;
99 | printf("direct write 8192 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
100 |
101 | start = time(NULL);
102 | fd = open("./direct_write.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC, 0644);
103 | for (i = 0; i < TEST_LOOPS; ++i) {
104 | pwrite(fd, buf, 12288, 0);
105 | }
106 | close(fd);
107 | end = time(NULL);
108 | cost = end - start;
109 | printf("direct write 12288 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
110 |
111 |
112 | return 0;
113 | }
114 |
115 |
--------------------------------------------------------------------------------
/fs/4.mmap_read_sync_nocache/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -Werror -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := mmap_read_sync_nocache
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/fs/4.mmap_read_sync_nocache/mmap_read_sync_nocache.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: mmap_write_performance.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 10/06/2016 12:20:48 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng (gfree.wind@gmail.com)
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #define _GNU_SOURCE
19 | #include
20 | #include
21 |
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 |
31 | #define TEST_LOOPS (5000000)
32 |
33 | int main(void)
34 | {
35 | int cost, i, fd;
36 | time_t start, end;
37 | char buf[20480];
38 |
39 | start = time(NULL);
40 | fd = open("./mmap_read.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC, 0644);
41 | ftruncate(fd, 4096);
42 | for (i = 0; i < TEST_LOOPS; ++i) {
43 | char *addr = mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0);
44 | memcpy(buf, addr, 4096);
45 | munmap(addr, 4096);
46 | }
47 | close(fd);
48 | end = time(NULL);
49 | cost = end - start;
50 | printf("mmap read 4096 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
51 |
52 | start = time(NULL);
53 | fd = open("./mmap_read.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC);
54 | ftruncate(fd, 8196);
55 | for (i = 0; i < TEST_LOOPS; ++i) {
56 | char *addr = mmap(NULL, 8196, PROT_READ, MAP_SHARED, fd, 0);
57 | memcpy(buf, addr, 8196);
58 | munmap(addr, 8196);
59 | }
60 | close(fd);
61 | end = time(NULL);
62 | cost = end - start;
63 | printf("mmap read 8196 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
64 |
65 | start = time(NULL);
66 | fd = open("./mmap_read.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC);
67 | ftruncate(fd, 12288);
68 | for (i = 0; i < TEST_LOOPS; ++i) {
69 | char *addr = mmap(NULL, 12288, PROT_READ, MAP_SHARED, fd, 0);
70 | memcpy(buf, addr, 12288);
71 | munmap(addr, 12288);
72 | }
73 | close(fd);
74 | end = time(NULL);
75 | cost = end - start;
76 | printf("mmap read 12288 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
77 |
78 |
79 | start = time(NULL);
80 | fd = open("./direct_read.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC, 0644);
81 | ftruncate(fd, 4096);
82 | for (i = 0; i < TEST_LOOPS; ++i) {
83 | pread(fd, buf, 4096, 0);
84 | }
85 | close(fd);
86 | end = time(NULL);
87 | cost = end - start;
88 | printf("direct read 4096 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
89 |
90 | start = time(NULL);
91 | fd = open("./direct_read.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC, 0644);
92 | ftruncate(fd, 8192);
93 | for (i = 0; i < TEST_LOOPS; ++i) {
94 | pread(fd, buf, 8192, 0);
95 | }
96 | close(fd);
97 | end = time(NULL);
98 | cost = end - start;
99 | printf("direct read 8192 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
100 |
101 | start = time(NULL);
102 | fd = open("./direct_read.txt", O_CREAT|O_RDWR|O_TRUNC|O_DIRECT|O_SYNC, 0644);
103 | ftruncate(fd, 12288);
104 | for (i = 0; i < TEST_LOOPS; ++i) {
105 | pread(fd, buf, 12288, 0);
106 | }
107 | close(fd);
108 | end = time(NULL);
109 | cost = end - start;
110 | printf("direct read 12288 bytes %u times costs %d secs\n", TEST_LOOPS, cost);
111 |
112 |
113 | return 0;
114 | }
115 |
116 |
--------------------------------------------------------------------------------
/fs/5.multi_thread_write_file/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -Werror -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := multi_thread_write_file
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/fs/5.multi_thread_write_file/multi_thread_write_file.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | //#define USE_CLIB
11 |
12 | #define TEST_FILE "./tmp.txt"
13 |
14 | #define LOOPS (1000000)
15 |
16 |
17 | #ifdef USE_CLIB
18 | struct thr_data {
19 | FILE *fp;
20 | const char *data;
21 | };
22 |
23 | static void * write_data(void *data)
24 | {
25 | struct thr_data *d;
26 | size_t len;
27 | int i;
28 |
29 | d = data;
30 | len = strlen(d->data);
31 | for (i = 0; i < LOOPS; ++i) {
32 | fwrite(d->data, len, 1, d->fp);
33 | }
34 |
35 | return NULL;
36 | }
37 |
38 | #else
39 | struct thr_data {
40 | int fd;
41 | const char *data;
42 | };
43 |
44 | static void *write_data(void *data)
45 | {
46 | struct thr_data *d;
47 | int i;
48 | size_t len;
49 |
50 | d = data;
51 | len = strlen(d->data);
52 | for (i = 0; i < LOOPS; ++i) {
53 | write(d->fd, d->data, len);
54 | }
55 |
56 | return NULL;
57 | }
58 | #endif
59 |
60 |
61 |
62 | int main(void)
63 | {
64 | pthread_t t1, t2, t3;
65 | struct thr_data d1, d2, d3;
66 |
67 | #ifdef USE_CLIB
68 | FILE *fp = fopen(TEST_FILE, "w");
69 | d1.fp = d2.fp = d3.fp = fp;
70 | #else
71 | //int fd = open(TEST_FILE, O_WRONLY|O_TRUNC);
72 | int fd = open(TEST_FILE, O_WRONLY|O_TRUNC|O_APPEND);
73 | d1.fd = d2.fd = d3.fd = fd;
74 | #endif
75 |
76 | d1.data = "aaaaaa\n";
77 | d2.data = "bbbbbb\n";
78 | d3.data = "cccccc\n";
79 |
80 | pthread_create(&t1, NULL, write_data, &d1);
81 | pthread_create(&t2, NULL, write_data, &d2);
82 | pthread_create(&t3, NULL, write_data, &d3);
83 |
84 | pthread_join(t1, NULL);
85 | pthread_join(t2, NULL);
86 | pthread_join(t3, NULL);
87 |
88 | #ifdef USE_CLIB
89 | fclose(fp);
90 | #else
91 | close(fd);
92 | #endif
93 |
94 | return 0;
95 | }
96 |
--------------------------------------------------------------------------------
/fs/README.md:
--------------------------------------------------------------------------------
1 | # 1.mmap_write_performance
2 |
3 | ## 问题
4 |
5 | 对比mmap和write的性能,哪个性能更好?
6 |
7 | ## 结论
8 |
9 | 利用mmap写文件的性能不如直接写文件。
10 |
11 | ## Question
12 |
13 | Compare the performance of mmap and write, which is better?
14 |
15 | ## Answer
16 |
17 | The performance of mmap write is worser than direct write.
18 |
19 | # 2.mmap_read_performance
20 |
21 | ## 问题
22 |
23 | 对比mmap和read的性能,哪个性能更好?
24 |
25 | ## 结论
26 |
27 | 利用mmap读文件的性能不如直接读文件。
28 |
29 | ## Question
30 |
31 | Compare the performance of mmap and read, which is better?
32 |
33 | ## Answer
34 |
35 | The performance of mmap read is worse than direct read.
36 |
37 | # 3.mmap_write_sync_nocache
38 |
39 | ## 问题
40 |
41 | 一般情况下,write都会使用cache,本例中禁止了cache,再次比较mmap和write的性能
42 |
43 | ## 结论
44 | 随着写入字节的增加,mmap消耗的时间也越来越多。
45 | 但是write消耗的时间并没有明显增加。
46 |
47 | ## Question
48 |
49 | When disable the write cache, how about the performance of mmap write and write?
50 |
51 | ## Answer
52 |
53 | The cost increases with bytes increasing when use mmap.
54 | But the cost of write does not increase.
55 |
56 | # 4.mmap_read_sync_nocache
57 |
58 | ## 问题
59 |
60 | 同上。本例中禁止了cache,再次比较mmap和read的性能
61 |
62 | ## 性能
63 | 随着读入字节的增加,mmap消耗的时间也在增加。
64 | 但是read消耗的时间增加的非常少
65 |
66 |
67 | # 5. multi_thread_write_file
68 |
69 | ## 问题
70 |
71 | 多线程同时对相同的文件进行写操作时,会有问题吗?
72 | 1)同时对相同的FILE*文件流进行写操作。
73 | 2)同时对相同的文件描述符进行写操作。
74 |
75 | ## 结论
76 | 1)当使用C库fwrite的时候,多线程同时写入文件没有问题。
77 | 2)当使用系统调用write时,多线程同时写入文件是非预期的行为可以使用O_APPEND标志避免这个问题。
78 |
79 |
--------------------------------------------------------------------------------
/ipc/1.mkfifo_with_unblock/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -Werror -shared -fPIC
9 | LDFLAGS :=
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := mkfifo_with_nonblock
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/ipc/1.mkfifo_with_unblock/mkfifo_with_nonblock.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: mkfifo_with_nonblock.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 09/25/2016 09:33:08 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng, gfree.wind@gmail.com
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include
19 | #include
20 | #include
21 | #include
22 |
23 | #include
24 | #include
25 | #include
26 | #include
27 |
28 | #define TEST_PIPE_FILE "./test.pipe"
29 |
30 | int main(void)
31 | {
32 | remove(TEST_PIPE_FILE);
33 | if (mkfifo(TEST_PIPE_FILE, 0644)) {
34 | printf("mkfifo failed, %s(%d)\n", strerror(errno), errno);
35 | return -1;
36 | }
37 |
38 | int fd = open(TEST_PIPE_FILE, O_WRONLY|O_NONBLOCK);
39 | if (fd == -1) {
40 | printf("open with O_WRONLY|O_NONBLOCK failed, %s(%d)\n",
41 | strerror(errno), errno);
42 | } else {
43 | printf("open with O_WRONLY|O_NONBLOCK is successful, return fd(%d)\n", fd);
44 | close(fd);
45 | }
46 |
47 | fd = open(TEST_PIPE_FILE, O_RDONLY|O_NONBLOCK);
48 | if (fd == -1) {
49 | printf("open with O_RDONLY|O_NONBLOCK failed, %s(%d)\n",
50 | strerror(errno), errno);
51 | } else {
52 | printf("open with O_RDONLY|O_NONBLOCK is successful, return fd(%d)\n", fd);
53 | close(fd);
54 | }
55 |
56 | return 0;
57 | }
58 |
--------------------------------------------------------------------------------
/ipc/2.unix_sock_recv_peer/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -g -Wall -Werror -shared -fPIC
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := unix_sock_recv_peer
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/ipc/2.unix_sock_recv_peer/unix_sock_recv_peer.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: tcp_close_with_data.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 08/31/2016 09:29:46 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng gfree.wind@gmail.com
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 |
30 | #define SERVER_PATH "./unix_server"
31 | #define CLIENT_PATH "./unix_client"
32 |
33 | #define BIND_UNIX_CLIENT
34 |
35 | static void* client_thread(void *data)
36 | {
37 | int fd = socket(AF_UNIX, SOCK_DGRAM, 0);
38 |
39 | #ifdef BIND_UNIX_CLIENT
40 | struct sockaddr_un cli_addr;
41 | memset(&cli_addr, 0, sizeof(cli_addr));
42 | cli_addr.sun_family = AF_UNIX;
43 | strcpy(cli_addr.sun_path, CLIENT_PATH);
44 | unlink(CLIENT_PATH);
45 | if (bind(fd, (struct sockaddr*)&cli_addr, sizeof(cli_addr))) {
46 | printf("Fail to bind client\n");
47 | exit(1);
48 | }
49 | #endif
50 |
51 | struct sockaddr_un serv_addr;
52 | memset(&serv_addr, 0, sizeof(serv_addr));
53 | serv_addr.sun_family = AF_UNIX;
54 | strcpy(serv_addr.sun_path, SERVER_PATH);
55 |
56 | sendto(fd, "123", 3, 0, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
57 |
58 | close(fd);
59 |
60 | return NULL;
61 |
62 | }
63 |
64 | int main(void)
65 | {
66 | pthread_t tid;
67 |
68 | signal(SIGPIPE, SIG_IGN);
69 |
70 | int server_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
71 | struct sockaddr_un serv_addr;
72 |
73 | memset(&serv_addr, 0, sizeof(serv_addr));
74 | serv_addr.sun_family = AF_UNIX;
75 | strcpy(serv_addr.sun_path, SERVER_PATH);
76 | unlink(SERVER_PATH);
77 | if (bind(server_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
78 | printf("Fail to bind\n");
79 | exit(-1);
80 | }
81 |
82 | pthread_create(&tid, NULL, client_thread, NULL);
83 |
84 | char buf[32] = {0};
85 | struct sockaddr_un peer_addr;
86 | socklen_t sock_len;
87 |
88 | memset(&peer_addr, 0, sizeof(peer_addr));
89 | sock_len = sizeof(peer_addr);
90 | recvfrom(server_fd, buf, sizeof(buf), 0, (struct sockaddr*)&peer_addr, &sock_len);
91 |
92 | printf("buf: %s\n", buf);
93 | printf("peer sun_path: %s\n", peer_addr.sun_path);
94 |
95 | close(server_fd);
96 | pthread_join(tid, NULL);
97 |
98 | return 0;
99 | }
100 |
--------------------------------------------------------------------------------
/ipc/README.md:
--------------------------------------------------------------------------------
1 | # 1.mkfifo_with_unblock
2 |
3 | ## 问题
4 |
5 | 调用mkfifo时,如果是只读打开且没有其它进程写入打开时,这个调用会阻塞。
6 | 同理,如果是写模式打开且没有其它进程读取打开时,这个调用也会阻塞。
7 | 那么当调用设置了非阻塞的标志时,会有什么现象呢?
8 |
9 | ## Question
10 |
11 | When invokes mkfifo with O_RDONLY and there is no process which opened
12 | the fifo with O_WRONLY already, this call would be blocked.
13 | It is blocked too that when invokes mkfifo with O_WRONLY and there is no
14 | process which opened the fifo with O_RDONLY.
15 |
16 | Then how about invokes mkfifo with O_NONBLOCK.
17 |
18 | ## 答案
19 | 如果在没有读取者时,非阻塞写模式打开管道文件会返回错误;
20 | 如果在没有写入者时,非阻塞读模式打开管道文件会成功打开.
21 |
22 | ## Answer
23 | mkfifo returns OK with O_RDONLY|O_NONBLOCK eventhough no O_WRONLY process, while
24 | it faied with O_WRONLY|O_NONBLOCK when no O_RDONLY process.
25 |
26 |
27 | # 2.unix_sock_recv_peer
28 |
29 | ## 问题
30 | 对于UNIX域套接字来说,如果调用recvfrom,得到的对端地址是什么呢?
31 |
32 | ## Question
33 | When UNIX socket invokes recvfrom, what peer info we could get?
34 |
35 | ## 答案
36 | 当Unix域套接字的客户端,也bind了一个文件,则服务端可以得到unix域的peer信息,就是客户端bind的地址,如sun_path就是bind的文件。
37 | 当Unix域套接字的客户端,没有bind,服务端得不到unix域的peer信息。
38 |
--------------------------------------------------------------------------------
/kernel/1.rwlock_spinlock_performance/Makefile:
--------------------------------------------------------------------------------
1 | obj-m := lock_test.o
2 |
3 | KDIR := /lib/modules/`uname -r`/build
4 |
5 | modules:
6 | make -C $(KDIR) M=$(PWD) modules
7 |
8 | clean:
9 | rm -f *.ko *.o *.mod.o *.mod.c *.order *.symvers
10 |
11 |
--------------------------------------------------------------------------------
/kernel/1.rwlock_spinlock_performance/lock_test.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | #define TEST_TIMES (100000000)
8 | #define ONE_SEC_NS (1000000000)
9 |
10 | static void time_cost(struct timespec *start, struct timespec *end,
11 | struct timespec *cost)
12 | {
13 | unsigned long long startns;
14 | unsigned long long endns;
15 |
16 | startns = start->tv_sec * ONE_SEC_NS + start->tv_nsec;
17 | endns = end->tv_sec * ONE_SEC_NS + end->tv_nsec;
18 | cost->tv_sec = end->tv_sec - start->tv_sec;
19 | if (end->tv_nsec >= start->tv_nsec) {
20 | cost->tv_nsec = end->tv_nsec - start->tv_nsec;
21 | } else {
22 | --cost->tv_sec;
23 | cost->tv_nsec = end->tv_nsec + ONE_SEC_NS - start->tv_nsec;
24 | }
25 |
26 | return;
27 | }
28 |
29 | static void lock_test(void)
30 | {
31 | DEFINE_RWLOCK(rwlock);
32 | spinlock_t spinlock;
33 | DEFINE_MUTEX(mutex);
34 | struct timespec start;
35 | struct timespec end;
36 | struct timespec cost;
37 | int i;
38 |
39 | preempt_disable();
40 | local_bh_disable();
41 | local_irq_disable();
42 |
43 | spin_lock_init(&spinlock);
44 |
45 | /* rwlock case */
46 | getnstimeofday(&start);
47 | for (i = 0; i < TEST_TIMES; ++i) {
48 | read_lock(&rwlock);
49 | read_unlock(&rwlock);
50 | }
51 | getnstimeofday(&end);
52 |
53 | time_cost(&start, &end, &cost);
54 |
55 | printk(KERN_INFO "wrlock start: %ld s, %ld ns\n",
56 | start.tv_sec, start.tv_nsec);
57 | printk(KERN_INFO "wrlock end: %ld s, %ld ns\n",
58 | end.tv_sec, end.tv_nsec);
59 | printk(KERN_INFO "wrlock costs %ld s, %ld ns\n",
60 | cost.tv_sec, cost.tv_nsec);
61 |
62 | /* spinlock case */
63 | getnstimeofday(&start);
64 | for (i = 0; i < TEST_TIMES; ++i) {
65 | spin_lock(&spinlock);
66 | spin_unlock(&spinlock);
67 | }
68 | getnstimeofday(&end);
69 |
70 | time_cost(&start, &end, &cost);
71 |
72 | printk(KERN_INFO "spinlock start: %ld s, %ld ns\n",
73 | start.tv_sec, start.tv_nsec);
74 | printk(KERN_INFO "spinlock end: %ld s, %ld ns\n",
75 | end.tv_sec, end.tv_nsec);
76 | printk(KERN_INFO "spinlock costs %ld s, %lu ns\n",
77 | cost.tv_sec, cost.tv_nsec);
78 |
79 | /* rcu case */
80 | getnstimeofday(&start);
81 | for (i = 0; i < TEST_TIMES; ++i) {
82 | rcu_read_lock();
83 | rcu_read_unlock();
84 | }
85 | getnstimeofday(&end);
86 |
87 | time_cost(&start, &end, &cost);
88 |
89 | printk(KERN_INFO "rculock start: %ld s, %ld ns\n",
90 | start.tv_sec, start.tv_nsec);
91 | printk(KERN_INFO "rculock end: %ld s, %ld ns\n",
92 | end.tv_sec, end.tv_nsec);
93 | printk(KERN_INFO "rculock costs %ld s, %lu ns\n",
94 | cost.tv_sec, cost.tv_nsec);
95 |
96 | /* mutex case */
97 | getnstimeofday(&start);
98 | for (i = 0; i < TEST_TIMES; ++i) {
99 | mutex_lock(&mutex);
100 | mutex_unlock(&mutex);
101 | }
102 | getnstimeofday(&end);
103 |
104 | time_cost(&start, &end, &cost);
105 |
106 | printk(KERN_INFO "mutex start: %ld s, %ld ns\n",
107 | start.tv_sec, start.tv_nsec);
108 | printk(KERN_INFO "mutex end: %ld s, %ld ns\n",
109 | end.tv_sec, end.tv_nsec);
110 | printk(KERN_INFO "mutex costs %ld s, %lu ns\n",
111 | cost.tv_sec, cost.tv_nsec);
112 |
113 | local_irq_enable();
114 | local_bh_enable();
115 | preempt_enable();
116 | }
117 |
118 | static int lock_test_init(void)
119 | {
120 |
121 | printk(KERN_INFO "Lock test init\n");
122 |
123 | lock_test();
124 |
125 | printk(KERN_INFO "Lock test exit\n");
126 |
127 | /* Return -1 so that we needn't use rmmod to uninstall module */
128 | return -1;
129 | }
130 |
131 | static void lock_test_exit(void)
132 | {
133 | printk(KERN_INFO "Lock test exit\n");
134 | }
135 |
136 | module_init(lock_test_init);
137 | module_exit(lock_test_exit);
138 |
139 |
--------------------------------------------------------------------------------
/kernel/2.sleep_test/Makefile:
--------------------------------------------------------------------------------
1 | obj-m := sleep_test.o
2 |
3 | KDIR := /lib/modules/`uname -r`/build
4 |
5 | modules:
6 | make -C $(KDIR) M=$(PWD) modules
7 |
8 | clean:
9 | rm -f *.ko *.o *.mod.o *.mod.c *.order *.symvers
10 |
11 |
--------------------------------------------------------------------------------
/kernel/2.sleep_test/sleep_test.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 |
8 | #define USE_UNINTERRUPTIBLE
9 |
10 | static struct task_struct *sleep_task = NULL;
11 |
12 | static int thread_func(void *data)
13 | {
14 | while (1) {
15 | if (kthread_should_stop()) {
16 | break;
17 | }
18 |
19 | #ifdef USE_UNINTERRUPTIBLE
20 | //ssleep(1);
21 | schedule_timeout_uninterruptible(HZ);
22 | #else
23 |
24 | schedule_timeout_interruptible(HZ);
25 | #endif
26 | }
27 |
28 | return 0;
29 | }
30 |
31 | static int __init sleep_task_init(void)
32 | {
33 | sleep_task = kthread_create(thread_func, NULL, "sleep_task");
34 | if (IS_ERR(sleep_task)) {
35 | printk(KERN_ERR "sleep_task: kthread_create failed\n");
36 | sleep_task = NULL;
37 | return -1;
38 | }
39 |
40 | wake_up_process(sleep_task);
41 |
42 | printk(KERN_INFO "sleep_task: init successfully\n");
43 |
44 | return 0;
45 | }
46 |
47 | static void __exit sleep_task_exit(void)
48 | {
49 | if (sleep_task) {
50 | kthread_stop(sleep_task);
51 | sleep_task = NULL;
52 | }
53 |
54 | printk(KERN_INFO "sleep_task: exit successfully\n");
55 | }
56 |
57 | MODULE_LICENSE("GPL");
58 |
59 | module_init(sleep_task_init);
60 | module_exit(sleep_task_exit);
61 |
--------------------------------------------------------------------------------
/kernel/README.md:
--------------------------------------------------------------------------------
1 | # 1.rwlock_spinlock_performance
2 |
3 | ## 问题
4 |
5 | rwlock与spinlock的性能对比,哪个性能更优?
6 |
7 | ## Question
8 |
9 | How about the performance of rwlock and spinlock?
10 |
11 | ## Answer
12 |
13 | In the old kernel, the performance of rwlock is worse than spinlock.
14 | But it is better than spinlock in latest kernel.
15 |
16 | You could test it in your environment.
17 |
18 |
19 | # 2.sleep_test
20 |
21 | ## 问题
22 |
23 | 当线程sleep时,其状态为TASK_UNINTERRUPTIBLE和TASK_INTERRUPTIBLE有什么区别?
24 |
25 | ## Question
26 |
27 | What's the difference when task's state is sleep with TASK_UNINTERRUPTIBLE or TASK_INTERRUPTIBLE?
28 |
29 |
30 | ## Answer
31 |
32 | When task state is TASK_UNINTERRUPTIBLE, it is counted into the CPU load.
33 | You would find the CPU load is increasing always when enable the macro USE_UNINTERRUPTIBLE.
34 | BTW, the ssleep would set the task state as TASK_UNINTERRUPTIBLE.
35 |
36 | The following link is my old blog about this topic.
37 | http://www.linxh.blog.chinaunix.net/uid-23629988-id-3242488.html
38 |
--------------------------------------------------------------------------------
/mem/1.vsz_and_rss/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CXXFLAGS := -Wall -shared -std=c++11 -fPIC
9 | LDFLAGS :=
10 | CXX := g++
11 |
12 | SRCS := $(wildcard *.cpp)
13 | DEPS := $(patsubst %.cpp,%.d,$(SRCS))
14 | OBJS := $(patsubst %.cpp,%.o,$(SRCS))
15 |
16 |
17 | TARGET := vsz_and_rss
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CXX) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.cpp
25 | $(CXX) -M $(CXXFLAGS) $< > $@
26 |
27 | %.o:%.cpp
28 | $(CXX) -c $(CXXFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/mem/1.vsz_and_rss/vsz_and_rss.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: vsz_and_rss.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 09/25/2016 09:33:08 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng, gfree.wind@gmail.com
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include
19 | #include
20 | #include
21 |
22 | using namespace std;
23 |
24 | vector mems;
25 |
26 | static void alloc_mem(bool fill)
27 | {
28 | int i;
29 |
30 | for (i = 0; i < 512; ++i) {
31 | void *p = malloc(1024*1024);
32 | if (fill) {
33 | memset(p, 0, 1024*1024);
34 | }
35 | mems.push_back(p);
36 | }
37 |
38 | printf("Mem is allocated\n");
39 | }
40 |
41 | int main(int argc, const char **argv)
42 | {
43 | alloc_mem(argc >= 2);
44 | getchar();
45 | return 0;
46 | }
47 |
48 |
--------------------------------------------------------------------------------
/mem/README.md:
--------------------------------------------------------------------------------
1 | # 1.vsz_and_rss
2 |
3 | ## 问题
4 |
5 | 对比VSZ和RSS,当申请内存时,只会增加VSZ。
6 | 只有真正使用这块内存时,RSS才会增加。
7 | 也就是说,应用层分配内存时,内核仅仅是分配了地址空间,并没有建立与物理内存的
8 | 映射关系。
9 |
10 | ## Question
11 |
12 | Comparing with the VSZ and RSS.
13 | Only VSZ is increased when just allocate memory.
14 | The RSS is increased only when app uses the mem.
15 | In other words, when app allocates memories, kernel just allocates the virtual
16 | memory address without corresponding physical page.
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/networks/1.tcp_close_with_data/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -Werror -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := tcp_close_with_data
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/networks/1.tcp_close_with_data/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | There are one TCP server thread and one TCP client thread.
4 | At the first time, the server close fd after read all bytes from client.
5 | At the second time, the server close fd after accept.
6 |
7 | # Conclusion
8 |
9 | When close TCP socket, it sends the RST if there are some bytes which are
10 | not received by app.
11 | This behaviro is defined in the section 2.17 of RFC 2525.
12 |
13 | The following codes are from the kernel codes, tcp_close
14 |
15 | /* As outlined in RFC 2525, section 2.17, we send a RST here because
16 | * data was lost. To witness the awful effects of the old behavior of
17 | * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
18 | * GET in an FTP client, suspend the process, wait for the client to
19 | * advertise a zero window, then kill -9 the FTP client, wheee...
20 | * Note: timeout is always zero in such a case.
21 | */
22 | if (data_was_unread) {
23 | /* Unread data was tossed, zap the connection. */
24 | NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
25 | tcp_set_state(sk, TCP_CLOSE);
26 | tcp_send_active_reset(sk, sk->sk_allocation);
27 | } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
28 |
29 |
30 | server: receive 6 bytes: First
31 | server: close fd at the first time
32 | client: ret is 0
33 | server: close fd at the second time
34 | client: ret is -1: Connection reset by peer
35 |
36 | But the first close never cause RST is sent.
37 |
38 |
39 |
--------------------------------------------------------------------------------
/networks/1.tcp_close_with_data/tcp_close_with_data.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: tcp_close_with_data.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 08/31/2016 09:29:46 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng gfree.wind@gmail.com
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 |
31 | typedef int bool;
32 |
33 | #define true 1
34 | #define false 0
35 |
36 | static volatile bool g_server_listen = false;
37 |
38 | static void* client_thread(void *data)
39 | {
40 | int fd = socket(AF_INET, SOCK_STREAM, 0);
41 | int ret;
42 |
43 | // wait parent listen
44 | while (!g_server_listen) {
45 | sleep(1);
46 | }
47 |
48 | struct sockaddr_in serv_addr;
49 | memset(&serv_addr, 0, sizeof(serv_addr));
50 | serv_addr.sin_family = AF_INET;
51 | serv_addr.sin_addr.s_addr = 0x010007f;
52 | serv_addr.sin_port = htons(6000);
53 |
54 | // Fist time
55 | connect(fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
56 |
57 | send(fd, "First", sizeof("First"), 0);
58 |
59 | // parent close already
60 | char buf[2048];
61 | ret = read(fd, buf, 32);
62 | printf("client: ret is %d\n", ret);
63 | close(fd);
64 |
65 | fd = socket(AF_INET, SOCK_STREAM, 0);
66 | ret = connect(fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
67 | if (ret) {
68 | printf("connect failed: %s\n", strerror(errno));
69 | return 0;
70 | }
71 | send(fd, buf, 2048, 0);
72 |
73 | // parent close already
74 | ret = read(fd, buf, 32);
75 | printf("client: ret is %d: %s\n", ret, strerror(errno));
76 | close(fd);
77 |
78 | return NULL;
79 |
80 | }
81 |
82 | int main(void)
83 | {
84 | pthread_t tid;
85 | int ret;
86 |
87 | signal(SIGPIPE, SIG_IGN);
88 |
89 | pthread_create(&tid, NULL, client_thread, NULL);
90 |
91 | int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
92 | if (listen_fd == -1) {
93 | printf("socket failed\n");
94 | goto err1;
95 | }
96 |
97 | int opt = 1;
98 | setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
99 |
100 | struct sockaddr_in serv_addr;
101 |
102 | memset(&serv_addr, 0, sizeof(serv_addr));
103 | serv_addr.sin_family = AF_INET;
104 | serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
105 | serv_addr.sin_port = htons(6000);
106 |
107 | if (bind(listen_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
108 | printf("bind failed\n");
109 | goto err2;
110 | }
111 |
112 | if (listen(listen_fd, 5)) {
113 | printf("listen failed\n");
114 | goto err2;
115 | }
116 | g_server_listen = true;
117 |
118 | int client = accept(listen_fd, NULL, 0);
119 | if (client == -1) {
120 | printf("accept failed\n");
121 | goto err2;
122 | }
123 |
124 | /*
125 | First time:
126 | Server close the fd after receive all data
127 | */
128 | char buf[32] = {0};
129 | ret = read(client, buf, 32);
130 | printf("server: receive %d bytes: %s\n", ret, buf);
131 |
132 | close(client);
133 | printf("server: close fd at the first time\n");
134 |
135 | client = accept(listen_fd, NULL, 0);
136 |
137 | /*
138 | Second time:
139 | Server close the fd without reading data
140 | */
141 | /*We sleep 30 second here so we have time to observe the output of "tcpdump -i lo" and "ss",
142 | These commands will show the interactive between server and client, and where the data hold on
143 | */
144 |
145 | sleep(30);
146 | close(client);
147 | printf("server: close fd at the second time\n");
148 |
149 | err2:
150 | close(listen_fd);
151 | err1:
152 | pthread_join(tid, NULL);
153 |
154 | return 0;
155 | }
156 |
--------------------------------------------------------------------------------
/networks/10.udp_listen_unexpected_port/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := udp_listen_unexpected_port
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/networks/10.udp_listen_unexpected_port/udp_listen_unexpected_port.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include /* See NOTES */
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 |
13 | #include
14 |
15 | int main(void)
16 | {
17 | int sock;
18 |
19 | if((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
20 | exit(1);
21 | }
22 |
23 | int flags = fcntl(sock, F_GETFL, 0);
24 | fcntl(sock, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC);
25 |
26 | struct sockaddr_in serv_addr;
27 |
28 | bzero(&serv_addr, sizeof(serv_addr));
29 | serv_addr.sin_family = AF_INET;
30 | serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
31 | serv_addr.sin_port = htons(50505);
32 |
33 | char msg[4];
34 | sendto(sock, (char*)&msg, sizeof(msg), 0, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
35 |
36 | return 0;
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/networks/2.tcp_push_packet/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := tcp_force_push
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/networks/2.tcp_push_packet/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | How to make sure kernel send one packet when call send every time
4 |
5 | # Conclusion
6 |
7 | TCP_NODELAY option:
8 | Enable TCP_NODELAY, it could send one TCP packet with PUSH every send call.
9 |
10 | int opt = 1;
11 | setsockopt(fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
12 |
13 |
14 | Packet Trace:
15 | tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
16 | listening on lo, link-type EN10MB (Ethernet), capture size 65535 bytes
17 | 22:22:20.926263 IP 127.0.0.1.46806 > 127.0.16.0.6000: Flags [S], seq 2443224076, win 43690, options [mss 65495,sackOK,TS val 398752434 ecr 0,nop,wscale 7], length 0
18 | 22:22:20.926305 IP 127.0.16.0.6000 > 127.0.0.1.46806: Flags [S.], seq 2966002025, ack 2443224077, win 43690, options [mss 65495,sackOK,TS val 398752434 ecr 398752434,nop,wscale 7], length 0
19 | 22:22:20.926331 IP 127.0.0.1.46806 > 127.0.16.0.6000: Flags [.], ack 1, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 0
20 | 22:22:20.926371 IP 127.0.0.1.46806 > 127.0.16.0.6000: Flags [P.], seq 1:2, ack 1, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 1
21 | 22:22:20.926404 IP 127.0.0.1.46806 > 127.0.16.0.6000: Flags [P.], seq 2:3, ack 1, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 1
22 | 22:22:20.926426 IP 127.0.0.1.46806 > 127.0.16.0.6000: Flags [P.], seq 3:4, ack 1, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 1
23 | 22:22:20.926428 IP 127.0.16.0.6000 > 127.0.0.1.46806: Flags [.], ack 2, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 0
24 | 22:22:20.926442 IP 127.0.0.1.46806 > 127.0.16.0.6000: Flags [P.], seq 4:5, ack 1, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 1
25 | 22:22:20.926458 IP 127.0.16.0.6000 > 127.0.0.1.46806: Flags [.], ack 3, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 0
26 | 22:22:20.926463 IP 127.0.0.1.46806 > 127.0.16.0.6000: Flags [P.], seq 5:6, ack 1, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 1
27 | 22:22:20.926474 IP 127.0.16.0.6000 > 127.0.0.1.46806: Flags [.], ack 4, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 0
28 | 22:22:20.926494 IP 127.0.16.0.6000 > 127.0.0.1.46806: Flags [.], ack 5, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 0
29 | 22:22:20.926493 IP 127.0.0.1.46806 > 127.0.16.0.6000: Flags [F.], seq 6, ack 1, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 0
30 | 22:22:20.926509 IP 127.0.16.0.6000 > 127.0.0.1.46806: Flags [.], ack 6, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 0
31 | 22:22:20.927565 IP 127.0.16.0.6000 > 127.0.0.1.46806: Flags [F.], seq 1, ack 7, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 0
32 | 22:22:20.927613 IP 127.0.0.1.46806 > 127.0.16.0.6000: Flags [.], ack 2, win 342, options [nop,nop,TS val 398752434 ecr 398752434], length 0
33 |
--------------------------------------------------------------------------------
/networks/2.tcp_push_packet/tcp_force_push.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: tcp_close_with_data.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 08/31/2016 09:29:46 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng gfree.wind@gmail.com
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 |
32 |
33 | #define ENABLE_NODELAY_TEST
34 | typedef int bool;
35 |
36 | #define true 1
37 | #define false 0
38 |
39 | #define PACKET_CNT 5
40 |
41 | static volatile bool g_server_listen = false;
42 |
43 | static void* client_thread(void *data)
44 | {
45 | int fd = socket(AF_INET, SOCK_STREAM, 0);
46 | int i;
47 | int opt;
48 |
49 | // wait parent listen
50 | while (!g_server_listen) {
51 | sleep(1);
52 | }
53 |
54 | struct sockaddr_in serv_addr;
55 | memset(&serv_addr, 0, sizeof(serv_addr));
56 | serv_addr.sin_family = AF_INET;
57 | serv_addr.sin_addr.s_addr = 0x010007f;
58 | serv_addr.sin_port = htons(6000);
59 |
60 | connect(fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
61 | #ifdef ENABLE_NODELAY_TEST
62 | /* Enable TCP_NODELAY, it could force PUSH */
63 | opt = 1;
64 | setsockopt(fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
65 | #else
66 | /* Disable TCP_CORK, it dosn't make sure force PUSH */
67 | opt = 0;
68 | setsockopt(fd, SOL_TCP, TCP_CORK, &opt, sizeof(opt));
69 | #endif
70 |
71 | for (i = 0; i < PACKET_CNT; ++i) {
72 | send(fd, "1", 1, 0);
73 | #ifndef ENABLE_NODELAY_TEST
74 | opt = 0;
75 | setsockopt(fd, SOL_TCP, TCP_CORK, &opt, sizeof(opt));
76 | #endif
77 | }
78 | close(fd);
79 |
80 | return NULL;
81 |
82 | }
83 |
84 | int main(void)
85 | {
86 | pthread_t tid;
87 | int ret;
88 | int i;
89 |
90 | signal(SIGPIPE, SIG_IGN);
91 |
92 | pthread_create(&tid, NULL, client_thread, NULL);
93 |
94 | int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
95 | if (listen_fd == -1) {
96 | printf("socket failed\n");
97 | goto err1;
98 | }
99 |
100 | int opt = 1;
101 | setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
102 |
103 | struct sockaddr_in serv_addr;
104 |
105 | memset(&serv_addr, 0, sizeof(serv_addr));
106 | serv_addr.sin_family = AF_INET;
107 | serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
108 | serv_addr.sin_port = htons(6000);
109 |
110 | if (bind(listen_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
111 | printf("bind failed\n");
112 | goto err2;
113 | }
114 |
115 | if (listen(listen_fd, 5)) {
116 | printf("listen failed\n");
117 | goto err2;
118 | }
119 | g_server_listen = true;
120 |
121 | int client = accept(listen_fd, NULL, 0);
122 | if (client == -1) {
123 | printf("accept failed\n");
124 | goto err2;
125 | }
126 |
127 | char buf[32];
128 | for (i = 0; i < PACKET_CNT; ++i) {
129 | memset(buf, 0, sizeof(buf));
130 | ret = read(client, buf, 32);
131 | printf("server: recive %d bytes: %s\n", ret, buf);
132 | }
133 |
134 | close(client);
135 | printf("server: close fd at the first time\n");
136 |
137 | err2:
138 | close(listen_fd);
139 | err1:
140 | pthread_join(tid, NULL);
141 |
142 | return 0;
143 | }
144 |
--------------------------------------------------------------------------------
/networks/3.tcp_unread_hit_rst/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := tcp_unread_rst
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/networks/3.tcp_unread_hit_rst/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | How about the return value of tcp read when receive one TCP RST?
4 | There are two threads.
5 | The server closes the socket after receives the client packet and left the packet in the socket.
6 | So it would trigger one TCP RST to client from server.
7 |
8 | # Conclusion
9 |
10 | The read returns "-1", and errno is set as "ECONNRESET","Connection reset by peer".
11 |
--------------------------------------------------------------------------------
/networks/3.tcp_unread_hit_rst/tcp_unread_rst.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: tcp_close_with_data.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 08/31/2016 09:29:46 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng gfree.wind@gmail.com
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 |
33 | typedef int bool;
34 |
35 | #define true 1
36 | #define false 0
37 |
38 | #define PACKET_CNT 5
39 |
40 | static volatile bool g_server_listen = false;
41 | static volatile bool g_client_send = false;
42 | static volatile bool g_server_close = false;
43 |
44 | static void* client_thread(void *data)
45 | {
46 | int fd = socket(AF_INET, SOCK_STREAM, 0);
47 | int i;
48 | int opt;
49 |
50 | // wait parent listen
51 | while (!g_server_listen) {
52 | sleep(1);
53 | }
54 |
55 | struct sockaddr_in serv_addr;
56 | memset(&serv_addr, 0, sizeof(serv_addr));
57 | serv_addr.sin_family = AF_INET;
58 | serv_addr.sin_addr.s_addr = 0x010007f;
59 | serv_addr.sin_port = htons(6000);
60 |
61 | connect(fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
62 | /* Enable TCP_NODELAY, it could force PUSH */
63 | opt = 1;
64 | setsockopt(fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
65 |
66 | for (i = 0; i < PACKET_CNT; ++i) {
67 | send(fd, "1", 1, 0);
68 | }
69 | g_client_send = true;
70 |
71 | while (!g_server_close) {
72 | sleep(1);
73 | }
74 |
75 | char buf[32];
76 | int ret = read(fd, buf, sizeof(buf));
77 |
78 | printf("ret: %d. error: %s(%d)\n", ret, strerror(errno), errno);
79 |
80 | close(fd);
81 |
82 | return NULL;
83 |
84 | }
85 |
86 | int main(void)
87 | {
88 | pthread_t tid;
89 |
90 | signal(SIGPIPE, SIG_IGN);
91 |
92 | pthread_create(&tid, NULL, client_thread, NULL);
93 |
94 | int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
95 | if (listen_fd == -1) {
96 | printf("socket failed\n");
97 | goto err1;
98 | }
99 |
100 | int opt = 1;
101 | setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
102 |
103 | struct sockaddr_in serv_addr;
104 |
105 | memset(&serv_addr, 0, sizeof(serv_addr));
106 | serv_addr.sin_family = AF_INET;
107 | serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
108 | serv_addr.sin_port = htons(6000);
109 |
110 | if (bind(listen_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
111 | printf("bind failed\n");
112 | goto err2;
113 | }
114 |
115 | if (listen(listen_fd, 5)) {
116 | printf("listen failed\n");
117 | goto err2;
118 | }
119 | g_server_listen = true;
120 |
121 | int client = accept(listen_fd, NULL, 0);
122 | if (client == -1) {
123 | printf("accept failed\n");
124 | goto err2;
125 | }
126 |
127 | if (!g_client_send) {
128 | sleep(1);
129 | }
130 |
131 | close(client);
132 | printf("server: close fd\n");
133 | g_server_close = true;
134 |
135 | err2:
136 | close(listen_fd);
137 | err1:
138 | pthread_join(tid, NULL);
139 |
140 | return 0;
141 | }
142 |
--------------------------------------------------------------------------------
/networks/4.reuse_addr_option/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := reuse_addr_option
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/networks/4.reuse_addr_option/reuse_addr_option.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include /* See NOTES */
6 | #include
7 | #include
8 | #include
9 | #include
10 |
11 | #define LOCAL_PORT (12345)
12 |
13 | static void test_udp_any_addr_same_port_diff_ifs(void)
14 | {
15 | int udp_fd1 = socket(AF_INET, SOCK_DGRAM, 0);
16 | int udp_fd2 = socket(AF_INET, SOCK_DGRAM, 0);
17 |
18 | struct sockaddr_in addr_in;
19 | memset(&addr_in, 0, sizeof(addr_in));
20 | addr_in.sin_family = AF_INET;
21 | addr_in.sin_port = htons(LOCAL_PORT);
22 | addr_in.sin_addr.s_addr = INADDR_ANY;
23 |
24 | char *opt = "eth0";
25 | if (setsockopt(udp_fd1, SOL_SOCKET, SO_BINDTODEVICE, opt, strlen(opt))) {
26 | printf("UDP1 fail to bind eth0. %s:%d\n", strerror(errno), errno);
27 | }
28 | opt = "eth1";
29 | if (setsockopt(udp_fd2, SOL_SOCKET, SO_BINDTODEVICE, opt, strlen(opt))) {
30 | printf("UDP2 fail to bind eth1. %s:%d\n", strerror(errno), errno);
31 | }
32 |
33 | if (bind(udp_fd1, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
34 | printf("UDP1 fail to bind any addr and port(%d) on eth0\n", LOCAL_PORT);
35 | }
36 |
37 | if (bind(udp_fd2, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
38 | printf("UDP2 fail to bind any addr and port(%d) on eth1 \n", LOCAL_PORT);
39 | }
40 |
41 | close(udp_fd1);
42 | close(udp_fd2);
43 |
44 | printf("UDP could bind two any addrs with same port and diff ifs without SO_REUSEADDR\n");
45 | }
46 |
47 |
48 | static void test_udp_diff_addr_same_port(struct in_addr *addr)
49 | {
50 | int udp_fd1 = socket(AF_INET, SOCK_DGRAM, 0);
51 | int udp_fd2 = socket(AF_INET, SOCK_DGRAM, 0);
52 |
53 | struct sockaddr_in addr_in;
54 | memset(&addr_in, 0, sizeof(addr_in));
55 | addr_in.sin_family = AF_INET;
56 | addr_in.sin_port = htons(LOCAL_PORT);
57 | addr_in.sin_addr = *addr;
58 |
59 | if (bind(udp_fd1, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
60 | printf("UDP1 fail to bind local addr and port(%d)\n", LOCAL_PORT);
61 | }
62 |
63 | addr_in.sin_addr.s_addr = 0x0100007f;
64 | if (bind(udp_fd2, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
65 | printf("UDP2 fail to bind any addr and port(%d)\n", LOCAL_PORT);
66 | }
67 |
68 | close(udp_fd1);
69 | close(udp_fd2);
70 |
71 | printf("UDP could bind two different addr with same port without SO_REUSEADDR\n");
72 | }
73 |
74 | static void test_udp_any_addr_same_port(void)
75 | {
76 | int udp_fd1 = socket(AF_INET, SOCK_DGRAM, 0);
77 | int udp_fd2 = socket(AF_INET, SOCK_DGRAM, 0);
78 |
79 | struct sockaddr_in addr_in;
80 | memset(&addr_in, 0, sizeof(addr_in));
81 | addr_in.sin_family = AF_INET;
82 | addr_in.sin_port = htons(LOCAL_PORT);
83 | addr_in.sin_addr.s_addr = INADDR_ANY;
84 |
85 | int enable = 1;
86 | setsockopt(udp_fd1, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
87 | setsockopt(udp_fd2, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
88 |
89 | if (bind(udp_fd1, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
90 | printf("UDP1 fail to bind any addr and port(%d)\n", LOCAL_PORT);
91 | }
92 |
93 | if (bind(udp_fd2, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
94 | printf("UDP2 fail to bind any addr and port(%d)\n", LOCAL_PORT);
95 | }
96 |
97 | close(udp_fd1);
98 | close(udp_fd2);
99 |
100 | printf("UDP could bind two any addrs with same port with SO_REUSEADDR\n");
101 | }
102 |
103 | static void test_udp_any_and_local_addr_same_port(struct in_addr *addr)
104 | {
105 | int udp_fd1 = socket(AF_INET, SOCK_DGRAM, 0);
106 | int udp_fd2 = socket(AF_INET, SOCK_DGRAM, 0);
107 |
108 | struct sockaddr_in addr_in;
109 | memset(&addr_in, 0, sizeof(addr_in));
110 | addr_in.sin_family = AF_INET;
111 | addr_in.sin_port = htons(LOCAL_PORT);
112 | addr_in.sin_addr.s_addr = INADDR_ANY;
113 |
114 | int enable = 1;
115 | setsockopt(udp_fd1, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
116 | setsockopt(udp_fd2, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
117 |
118 | if (bind(udp_fd1, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
119 | printf("UDP1 fail to bind any addr and port(%d)\n", LOCAL_PORT);
120 | }
121 |
122 | addr_in.sin_addr= *addr;
123 |
124 | if (bind(udp_fd2, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
125 | printf("UDP2 fail to bind local addr and port(%d)\n", LOCAL_PORT);
126 | }
127 |
128 | close(udp_fd1);
129 | close(udp_fd2);
130 |
131 | printf("UDP could bind any addr and one local addr with same port with SO_REUSEADDR\n");
132 | }
133 |
134 | static void test_udp_local_and_any_addr_same_port(struct in_addr *addr)
135 | {
136 | int udp_fd1 = socket(AF_INET, SOCK_DGRAM, 0);
137 | int udp_fd2 = socket(AF_INET, SOCK_DGRAM, 0);
138 |
139 | struct sockaddr_in addr_in;
140 | memset(&addr_in, 0, sizeof(addr_in));
141 | addr_in.sin_family = AF_INET;
142 | addr_in.sin_port = htons(LOCAL_PORT);
143 | addr_in.sin_addr = *addr;
144 |
145 | int enable = 1;
146 | setsockopt(udp_fd1, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
147 | setsockopt(udp_fd2, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
148 |
149 | if (bind(udp_fd1, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
150 | printf("UDP1 fail to bind local addr and port(%d)\n", LOCAL_PORT);
151 | }
152 |
153 | addr_in.sin_addr.s_addr = INADDR_ANY;
154 |
155 | if (bind(udp_fd2, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
156 | printf("UDP2 fail to bind any addr and port(%d)\n", LOCAL_PORT);
157 | }
158 |
159 | close(udp_fd1);
160 | close(udp_fd2);
161 | printf("UDP could bind one local addr and one any addr with same port with SO_REUSEADDR\n");
162 | }
163 |
164 | static void test_udp_local_addr_same_port(struct in_addr *addr)
165 | {
166 | int udp_fd1 = socket(AF_INET, SOCK_DGRAM, 0);
167 | int udp_fd2 = socket(AF_INET, SOCK_DGRAM, 0);
168 |
169 | struct sockaddr_in addr_in;
170 | memset(&addr_in, 0, sizeof(addr_in));
171 | addr_in.sin_family = AF_INET;
172 | addr_in.sin_port = htons(LOCAL_PORT);
173 | addr_in.sin_addr = *addr;
174 |
175 | int enable = 1;
176 | setsockopt(udp_fd1, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
177 | setsockopt(udp_fd2, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
178 |
179 | if (bind(udp_fd1, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
180 | printf("UDP1 fail to bind port(%d)\n", LOCAL_PORT);
181 | }
182 |
183 | if (bind(udp_fd2, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
184 | printf("UDP2 fail to bind port(%d)\n", LOCAL_PORT);
185 | }
186 |
187 | close(udp_fd1);
188 | close(udp_fd2);
189 |
190 | printf("UDP could bind two local addrs and port with SO_REUSEADDR\n");
191 | }
192 |
193 | static void test_tcp_udp_same_port(struct in_addr *addr)
194 | {
195 | int tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
196 | if (tcp_fd == -1) {
197 | printf("Fail to create tcp fd\n");
198 | exit(1);
199 | }
200 | int udp_fd = socket(AF_INET, SOCK_DGRAM, 0);
201 | if (udp_fd == -1) {
202 | printf("Fail to creat udp fd\n");
203 | exit(1);
204 | }
205 |
206 | struct sockaddr_in addr_in;
207 | memset(&addr_in, 0, sizeof(addr_in));
208 | addr_in.sin_family = AF_INET;
209 | addr_in.sin_port = htons(LOCAL_PORT);
210 | addr_in.sin_addr = *addr;
211 |
212 | if (bind(tcp_fd, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
213 | printf("TCP fail to bind port(%d)\n", LOCAL_PORT);
214 | }
215 |
216 | if (bind(udp_fd, (const struct sockaddr *)&addr_in, sizeof(addr_in)) != 0) {
217 | printf("UDP fail to bind port(%d)\n", LOCAL_PORT);
218 | }
219 |
220 | close(tcp_fd);
221 | close(udp_fd);
222 |
223 | printf("TCP and UDP could bind same port seperately\n");
224 | }
225 |
226 | int main(int argc, const char **argv)
227 | {
228 | struct in_addr addr;
229 |
230 | if (argc < 2) {
231 | printf("Please specify local IP address\n");
232 | return 1;
233 | }
234 |
235 | memset(&addr, 0, sizeof(addr));
236 | if (inet_pton(AF_INET, argv[1], &addr) != 1) {
237 | printf("Invalid IP address");
238 | return 1;
239 | }
240 |
241 |
242 | test_tcp_udp_same_port(&addr);
243 | test_udp_local_addr_same_port(&addr);
244 | test_udp_local_and_any_addr_same_port(&addr);
245 | test_udp_any_and_local_addr_same_port(&addr);
246 | test_udp_any_addr_same_port();
247 | test_udp_diff_addr_same_port(&addr);
248 | test_udp_any_addr_same_port_diff_ifs();
249 |
250 | return 0;
251 | }
252 |
253 |
254 |
--------------------------------------------------------------------------------
/networks/5.no_listen_tcp_conn/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := no_listen_tcp_conn
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/networks/5.no_listen_tcp_conn/no_listen_tcp_conn.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: no_listen_tcp_conn.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 06/18/2017 10:04:07 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: YOUR NAME (),
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include /* See NOTES */
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 |
27 | #define LOCAL_IP_ADDR (0x7F000001)
28 | #define LOCAL_TCP_PORT (34567)
29 |
30 | int main(void)
31 | {
32 | struct sockaddr_in local, peer;
33 | int ret;
34 | char buf[128];
35 | int sock = socket(AF_INET, SOCK_STREAM, 0);
36 |
37 | memset(&local, 0, sizeof(local));
38 | memset(&peer, 0, sizeof(peer));
39 |
40 | local.sin_family = AF_INET;
41 | local.sin_port = htons(LOCAL_TCP_PORT);
42 | local.sin_addr.s_addr = htonl(LOCAL_IP_ADDR);
43 |
44 | peer = local;
45 |
46 | int flag = 1;
47 | ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
48 | if (ret == -1) {
49 | printf("Fail to setsocket SO_REUSEADDR: %s\n", strerror(errno));
50 | exit(1);
51 | }
52 |
53 | ret = bind(sock, (const struct sockaddr *)&local, sizeof(local));
54 | ret = connect(sock, (const struct sockaddr *)&peer, sizeof(peer));
55 |
56 | if (ret) {
57 | printf("Fail to connect myself: %s\n", strerror(errno));
58 | exit(1);
59 | }
60 | printf("Connect to myself successfully\n");
61 |
62 | strcpy(buf, "Hello, myself~");
63 | send(sock, buf, strlen(buf), 0);
64 |
65 | memset(buf, 0, sizeof(buf));
66 | recv(sock, buf, sizeof(buf), 0);
67 |
68 | printf("Recv the msg: %s\n", buf);
69 | close(sock);
70 | return 0;
71 | }
72 |
73 |
--------------------------------------------------------------------------------
/networks/6.tcp_keepalive_reporter/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := tcp_keepalive_reporter
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/networks/6.tcp_keepalive_reporter/tcp_keepalive_report.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: tcp_keepalive_reporter
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 06/18/2017 10:04:07 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: YOUR NAME (),
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include /* See NOTES */
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | /* According to POSIX.1-2001 */
27 | #include
28 | /* According to earlier standards */
29 | #include
30 | #include
31 | #include
32 | #include
33 | #include
34 | #include
35 |
36 |
37 | #define PEER_ADDR (0x7F000001)
38 | #define PEER_PORT (34567)
39 |
40 | //#define USE_SELECT
41 | #define USE_EPOLL
42 |
43 | int main(void)
44 | {
45 | struct sockaddr_in peer;
46 | int ret;
47 | int sock = socket(AF_INET, SOCK_STREAM, 0);
48 | int optval;
49 | int err;
50 | char buf[512];
51 | socklen_t len = sizeof(err);
52 |
53 | memset(&peer, 0, sizeof(peer));
54 |
55 | peer.sin_family = AF_INET;
56 | peer.sin_port = htons(PEER_PORT);
57 | peer.sin_addr.s_addr = htonl(PEER_ADDR);
58 |
59 |
60 | ret = connect(sock, (const struct sockaddr *)&peer, sizeof(peer));
61 |
62 | if (ret) {
63 | printf("Fail to connect myself: %s\n", strerror(errno));
64 | exit(1);
65 | }
66 | printf("Connect successfully\n");
67 |
68 | optval = 1;
69 | ret = setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));
70 | if (ret) {
71 | printf("Fail to set SO_KEEPALIVE\n");
72 | exit(1);
73 | }
74 |
75 | optval = 5;
76 | ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &optval, sizeof(optval));
77 | if (ret) {
78 | printf("Fail to set TCP_KEEPIDLE: %s\n", strerror(errno));
79 | exit(1);
80 | }
81 | optval = 2;
82 | ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &optval, sizeof(optval));
83 | if (ret) {
84 | printf("Fail to set TCP_KEEPINTVL: %s\n", strerror(errno));
85 | exit(1);
86 | }
87 | optval = 3;
88 | ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &optval, sizeof(optval));
89 | if (ret) {
90 | printf("Fail to set TCP_KEEPCNT: %s\n", strerror(errno));
91 | exit(1);
92 | }
93 |
94 |
95 | #ifdef USE_SELECT
96 | fd_set rfds;
97 |
98 | FD_ZERO(&rfds);
99 |
100 | FD_SET(sock, &rfds);
101 |
102 | ret = select(sock+1, &rfds, NULL, NULL, NULL);
103 | if (ret) {
104 | printf("select returns %d\n", ret);
105 | if (FD_ISSET(sock, &rfds)) {
106 | printf("Receive RD event by select\n");
107 | }
108 | }
109 | #endif
110 |
111 | #ifdef USE_EPOLL
112 | int ep = epoll_create(1024);
113 | if (ep == -1) {
114 | printf("Fail to epoll_create: %s\n", strerror(errno));
115 | exit(1);
116 | }
117 |
118 | struct epoll_event evt;
119 |
120 | memset(&evt, 0, sizeof(evt));
121 | evt.events |= EPOLLIN;
122 | evt.data.fd = sock;
123 |
124 | ret = epoll_ctl(ep, EPOLL_CTL_ADD, sock, &evt);
125 | if (ret) {
126 | printf("Fail to epoll_ctl: %s\n", strerror(errno));
127 | exit(1);
128 | }
129 |
130 | memset(&evt, 0, sizeof(evt));
131 | ret = epoll_wait(ep, &evt, 1, -1);
132 | if (ret) {
133 | if (evt.events & EPOLLIN) {
134 | printf("Receive RD event by epoll\n");
135 | }
136 | }
137 |
138 | close(ep);
139 | #endif
140 |
141 | err = 0;
142 | ret = getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &len);
143 | if (ret) {
144 | printf("Fail to getsockopt\n");
145 | exit(1);
146 | }
147 | printf("sock err is %d\n", err);
148 |
149 | ret = read(sock, buf, 512);
150 | printf("Read %d bytes\n", ret);
151 |
152 | close(sock);
153 | return 0;
154 | }
155 |
156 |
--------------------------------------------------------------------------------
/networks/7.tcp_send_rst/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := tcp_send_rst
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/networks/7.tcp_send_rst/tcp_send_rst.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: tcp_keepalive_reporter
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 06/18/2017 10:04:07 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: YOUR NAME (),
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include /* See NOTES */
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | /* According to earlier standards */
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 |
33 |
34 | #define PEER_ADDR (0x7F000001)
35 | #define PEER_PORT (34567)
36 |
37 | int main(void)
38 | {
39 | struct sockaddr_in local, peer;
40 | struct linger linger;
41 | int ret;
42 | int sock = socket(AF_INET, SOCK_STREAM, 0);
43 |
44 | memset(&peer, 0, sizeof(peer));
45 |
46 | peer.sin_family = AF_INET;
47 | peer.sin_port = htons(PEER_PORT);
48 | peer.sin_addr.s_addr = htonl(PEER_ADDR);
49 | local = peer;
50 |
51 | int flag = 1;
52 | ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
53 | if (ret == -1) {
54 | printf("Fail to setsocket SO_REUSEADDR: %s\n", strerror(errno));
55 | exit(1);
56 | }
57 |
58 | ret = bind(sock, (const struct sockaddr *)&local, sizeof(local));
59 | if (ret) {
60 | printf("Fail to bind: %s\n", strerror(errno));
61 | exit(1);
62 | }
63 | ret = connect(sock, (const struct sockaddr *)&peer, sizeof(peer));
64 |
65 | if (ret) {
66 | printf("Fail to connect myself: %s\n", strerror(errno));
67 | exit(1);
68 | }
69 | printf("Connect successfully\n");
70 |
71 | memset(&linger, 0, sizeof(linger));
72 | linger.l_onoff = 1;
73 | linger.l_linger = 0;
74 |
75 | ret = setsockopt(sock, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
76 | if (ret) {
77 | printf("Fail to set linger\n");
78 | exit(1);
79 | }
80 |
81 | close(sock);
82 |
83 | printf("Done\n");
84 | return 0;
85 | }
86 |
87 |
--------------------------------------------------------------------------------
/networks/8.connect_until_fail/accpet_util_fail.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import sys
4 | import socket
5 |
6 | if __name__ == "__main__":
7 | if len(sys.argv) <= 2:
8 | print "Please specify the address & port"
9 | exit(1)
10 |
11 | addr = sys.argv[1]
12 | port = int(sys.argv[2])
13 | print "Listen {}:{}".format(addr, port)
14 |
15 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
16 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
17 | sock.bind((addr, port))
18 | sock.listen(1024)
19 |
20 | socks = []
21 | while True:
22 | try:
23 | new_sock = sock.accept()
24 | socks.append(new_sock)
25 | print "Establish {} connections".format(len(socks))
26 | except Exception as e:
27 | print "Unexpected error: " + str(e)
28 | break
29 |
--------------------------------------------------------------------------------
/networks/8.connect_until_fail/connect_until_fail.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import sys
4 | import socket
5 |
6 | if __name__ == "__main__":
7 | if len(sys.argv) <= 2:
8 | print "Please specify the address & port"
9 | exit(1)
10 |
11 | addr = sys.argv[1]
12 | port = int(sys.argv[2])
13 | print "Connect {}:{}".format(addr, port)
14 |
15 | socks = []
16 | while True:
17 | try:
18 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
19 | sock.connect((addr, port))
20 | print "Connect {} times".format((len(socks)))
21 | socks.append(sock)
22 | except Exception as e:
23 | print "Unexpect error:" + str(e)
24 | break
25 |
--------------------------------------------------------------------------------
/networks/9.tcp_unread_shutdown/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -g -shared -fPIC -std=gnu99
9 | LDFLAGS := -lpthread
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := tcp_unread_shutdown
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/networks/9.tcp_unread_shutdown/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | How about the return value of tcp read when receive one TCP RST?
4 | There are two threads.
5 | The server closes the socket after receives the client packet and left the packet in the socket.
6 | So it would trigger one TCP RST to client from server.
7 |
8 | # Conclusion
9 |
10 | The read returns "-1", and errno is set as "ECONNRESET","Connection reset by peer".
11 |
--------------------------------------------------------------------------------
/networks/9.tcp_unread_shutdown/tcp_unread_shutdown.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: tcp_close_with_data.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 08/31/2016 09:29:46 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: Gao Feng gfree.wind@gmail.com
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 |
33 | typedef int bool;
34 |
35 | #define true 1
36 | #define false 0
37 |
38 | #define PACKET_CNT 5
39 |
40 | static volatile bool g_server_listen = false;
41 | static volatile bool g_client_send = false;
42 | static volatile bool g_server_close = false;
43 |
44 | static void* client_thread(void *data)
45 | {
46 | int fd = socket(AF_INET, SOCK_STREAM, 0);
47 | int i;
48 | int opt;
49 |
50 | // wait parent listen
51 | while (!g_server_listen) {
52 | sleep(1);
53 | }
54 |
55 | struct sockaddr_in serv_addr;
56 | memset(&serv_addr, 0, sizeof(serv_addr));
57 | serv_addr.sin_family = AF_INET;
58 | serv_addr.sin_addr.s_addr = 0x010007f;
59 | serv_addr.sin_port = htons(6000);
60 |
61 | connect(fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
62 | /* Enable TCP_NODELAY, it could force PUSH */
63 | opt = 1;
64 | setsockopt(fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
65 |
66 | for (i = 0; i < PACKET_CNT; ++i) {
67 | send(fd, "1", 1, 0);
68 | }
69 | g_client_send = true;
70 |
71 | while (!g_server_close) {
72 | sleep(1);
73 | }
74 |
75 | char buf[32];
76 | int ret = read(fd, buf, sizeof(buf));
77 |
78 | printf("ret: %d. error: %s(%d)\n", ret, strerror(errno), errno);
79 |
80 | close(fd);
81 |
82 | return NULL;
83 |
84 | }
85 |
86 | int main(void)
87 | {
88 | pthread_t tid;
89 |
90 | signal(SIGPIPE, SIG_IGN);
91 |
92 | pthread_create(&tid, NULL, client_thread, NULL);
93 |
94 | int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
95 | if (listen_fd == -1) {
96 | printf("socket failed\n");
97 | goto err1;
98 | }
99 |
100 | int opt = 1;
101 | setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
102 |
103 | struct sockaddr_in serv_addr;
104 |
105 | memset(&serv_addr, 0, sizeof(serv_addr));
106 | serv_addr.sin_family = AF_INET;
107 | serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
108 | serv_addr.sin_port = htons(6000);
109 |
110 | if (bind(listen_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
111 | printf("bind failed\n");
112 | goto err2;
113 | }
114 |
115 | if (listen(listen_fd, 5)) {
116 | printf("listen failed\n");
117 | goto err2;
118 | }
119 | g_server_listen = true;
120 |
121 | int client = accept(listen_fd, NULL, 0);
122 | if (client == -1) {
123 | printf("accept failed\n");
124 | goto err2;
125 | }
126 |
127 | if (!g_client_send) {
128 | sleep(1);
129 | }
130 |
131 | shutdown(client, SHUT_RDWR);
132 | close(client);
133 | printf("server: close fd\n");
134 | g_server_close = true;
135 |
136 | err2:
137 | close(listen_fd);
138 | err1:
139 | pthread_join(tid, NULL);
140 |
141 | return 0;
142 | }
143 |
--------------------------------------------------------------------------------
/networks/README.md:
--------------------------------------------------------------------------------
1 | # 1.tcp_close_with_data
2 |
3 | ## 问题
4 |
5 | 当没有读取完所有的TCP数据,就关闭套接字,是否会有问题?
6 | 这种情况与读完数据再关闭是否一致?
7 |
8 | ## Question
9 |
10 | Is it ok that close the TCP socket before read all bytes?
11 | Is it same as that close fd after read all bytes?
12 |
13 | ## Answer
14 | No!
15 |
16 | # 2.tcp_push_packet
17 |
18 | ## 问题
19 |
20 | 如何让TCP协议栈不对数据做优化,一次send调用就对应一个数据包。
21 |
22 |
23 | # 3.tcp_read_hit_rst
24 |
25 | ## 问题
26 |
27 |
28 | 当tcp套接字read调用,遇到对端发送RST报文时,返回值是什么?
29 |
30 | ## Answer
31 |
32 | read返回-1,errno是ECONNRESET,即Connection reset by peer
33 |
34 |
35 | # 4.reuse_addr_option
36 |
37 |
38 | ## 问题
39 |
40 |
41 | 什么时候需要使用SO_REUSEADDR?
42 |
43 |
44 | ## Answer
45 |
46 |
47 | 当proto, addr, 和port三个元素都相同时,需要使用SO_REUSEADDR。
48 |
49 | 其中INADDR_ANY表示任意地址,其与所有地址视为相同。
50 |
51 |
52 | # 5.no_listen_tcp_conn
53 |
54 | ## 问题
55 | 没有listen调用,是否可以建立tcp连接
56 |
57 |
58 | # 6.tcp_keepalive_reporter
59 | 当TCP的KeepAlive机制判定连接超时,应用层如何得到通知。
60 |
61 |
62 |
63 | # 7.tcp_send_rst
64 | 应用层如何强制TCP发送RST中断连接。
65 |
66 |
67 | # 8.connect_until_fail
68 | 尝试一直连接,直到失败
69 |
70 | # 9.tcp_unread_shutdown
71 | 关闭未读数据的tcp端口
72 |
73 | # 10.udp_listen_unexpected_port
74 | 没有bind的udp socket,“监听”了非期望端口。
75 |
--------------------------------------------------------------------------------
/process/1.child_inherit_flock/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -Werror -shared -fPIC
9 | LDFLAGS :=
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := child_inherit_flock
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/process/1.child_inherit_flock/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | This prarent process flocks one file, then forks one child process. Then the parent exits directly, while the child sleeps 30 seconds.
4 | At that time, run this process again. You would find the second instance blocks until the child of first instance exits.
5 |
6 | # Conclusion
7 |
8 | The flock is shared between the parent and child process. Although the flock would be release automatically when process exits, it must be done until both of parent and child exit.
9 |
--------------------------------------------------------------------------------
/process/1.child_inherit_flock/child_inherit_flock.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: child_inherit_flock.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 08/26/2016 10:01:43 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: YOUR NAME (),
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include
19 | #include
20 |
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 |
28 | int main(void)
29 | {
30 | int fd = open("./test_flock.txt", O_RDWR|O_CREAT, 0644);
31 | if (fd == -1) {
32 | printf("Fail to open file\n");
33 | exit(1);
34 | }
35 |
36 | int ret = flock(fd, LOCK_EX);
37 | if (ret == -1) {
38 | printf("Fail to flock\n");
39 | exit(1);
40 | }
41 | printf("Parent get the flock at the first time\n");
42 |
43 | pid_t child = fork();
44 | if (child == -1) {
45 | printf("Fail to fork\n");
46 | exit(1);
47 | } else if (child == 0) {
48 | printf("Child sleeps now\n");
49 | sleep(30);
50 | printf("Child wakes up and exits\n");
51 | exit(1);
52 | }
53 |
54 | printf("Parent exit\n");
55 |
56 | return 0;
57 | }
58 |
59 |
--------------------------------------------------------------------------------
/process/2.child_share_flock/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -Werror -shared -fPIC
9 | LDFLAGS :=
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := child_inherit_flock
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/process/2.child_share_flock/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | The prarent process holds one flock, then forks one child process. Now the flock is shared between with child and parent. Then child sleeps 30 seconds, and parent releases the lock, then tries to get the lock again.
4 |
5 |
6 | # Conclusion
7 |
8 | The parent could get the flock immediately although child does not exit. Because the flock is shared between child and parent, actually there is one instance of flock between child and parent. So when the parent releases the flock, the child does not own the flock yet. So parent could get the lock again immediately.
9 |
10 |
11 |
--------------------------------------------------------------------------------
/process/2.child_share_flock/child_share_flock.c:
--------------------------------------------------------------------------------
1 | /*
2 | * =====================================================================================
3 | *
4 | * Filename: child_inherit_flock.c
5 | *
6 | * Description:
7 | *
8 | * Version: 1.0
9 | * Created: 08/26/2016 10:01:43 PM
10 | * Revision: none
11 | * Compiler: gcc
12 | *
13 | * Author: YOUR NAME (),
14 | * Company:
15 | *
16 | * =====================================================================================
17 | */
18 | #include
19 | #include
20 |
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 |
28 | int main(void)
29 | {
30 | int fd = open("./test_flock.txt", O_RDWR|O_CREAT, 0644);
31 | if (fd == -1) {
32 | printf("Fail to open file\n");
33 | exit(1);
34 | }
35 |
36 | int ret = flock(fd, LOCK_EX);
37 | if (ret == -1) {
38 | printf("Fail to flock\n");
39 | exit(1);
40 | }
41 | printf("Parent get the flock at the first time\n");
42 |
43 | pid_t child = fork();
44 | if (child == -1) {
45 | printf("Fail to fork\n");
46 | exit(1);
47 | } else if (child == 0) {
48 | printf("Child sleeps now\n");
49 | sleep(30);
50 | printf("Child wakes up and exits\n");
51 | exit(1);
52 | }
53 |
54 | flock(fd, LOCK_UN);
55 | printf("Parent release the lock\n");
56 | printf("Parent tries to get flock again\n");
57 | flock(fd, LOCK_EX);
58 | printf("Parent gets the lock at the second time\n");
59 |
60 | waitpid(child, NULL, 0);
61 |
62 | printf("Parent exit\n");
63 |
64 | return 0;
65 | }
66 |
67 |
--------------------------------------------------------------------------------
/process/3.fork_and_print/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -Werror -shared -fPIC
9 | LDFLAGS :=
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := fork_and_print
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/process/3.fork_and_print/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | The parent printfs string "Hello,", then forks one child, then printf "I'm parent\n".
4 | And the child printf "I'm child\n".
5 |
6 | How about the output?
7 |
8 | # Answer
9 |
10 | Hello, I'm parent
11 | Hello, I'm child
12 | or
13 | Hello, I'm child
14 | Hello, I'm parent
15 |
16 | # Conclusion
17 | Because the printf uses the line buffer by default, so the "Hello," is not printed acutally
18 | when parent forks child. Then the line buffer is inherited by child.
19 |
20 | So the child also could print "Hello, " likes its parent.
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/process/3.fork_and_print/fork_and_print.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 |
5 | #include
6 | #include
7 |
8 | int main(void)
9 | {
10 | pid_t child;
11 |
12 | printf("Hello, ");
13 |
14 | child = fork();
15 | if (child == -1) {
16 | printf("fork failed\n");
17 | exit(1);
18 | } else if (child == 0) {
19 | // Child
20 | printf("I'm child\n");
21 | exit(0);
22 | }
23 |
24 | // Parent
25 | printf("I'm parent\n");
26 |
27 | waitpid(child, NULL, 0);
28 |
29 | return 0;
30 | }
31 |
--------------------------------------------------------------------------------
/process/4.fork_with_fd/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -Werror -shared -fPIC
9 | LDFLAGS :=
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := fork_with_fd
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/process/4.fork_with_fd/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | The parent process opens one file "./test1.txt", and forks one child.
4 | Both of parent and child opens another file "./test2.txt" after fork.
5 | Then the parent writes "I'm parent\n" into these two files, while child does
6 | the same thing too.
7 |
8 | How about the content of these two files?
9 |
10 | # Answer
11 |
12 | ./test1.txt:
13 |
14 |
15 | I'm parent
16 |
17 | I'm child
18 |
19 | ./test2.txt
20 |
21 | I'm child
22 |
23 | Notic: The content may be different in your environment.
24 | The schedule policy of fork is decided by /proc/sys/kernel/sched_child_runs_first.
25 |
26 | Anyway, the parent and child overlap the content of "./test2.txt",
27 | but "./test1.txt" not.
28 |
29 | # Conclusion
30 | The fd of parent and child shares one same fd and owns same kernel struct which
31 | maintains the file offset. So the content of "./test1.txt" does not overlap.
32 |
33 | The fd which is created after fork owns its file strcture in kernel, so the file
34 | offset is not shared between parent and child.
35 |
36 |
37 |
--------------------------------------------------------------------------------
/process/4.fork_with_fd/fork_with_fd.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 |
10 | int main(void)
11 | {
12 | int fd1 = open("./test1.txt", O_WRONLY|O_CREAT, 0644);
13 | if (fd1 == -1) {
14 | printf("Fail to open ./test1.txt\n");
15 | exit(1);
16 | }
17 |
18 | pid_t child = fork();
19 | if (child == -1) {
20 | printf("Fail to fork\n");
21 | exit(1);
22 | } else if (child == 0) {
23 | // Child
24 | int fd2 = open("./test2.txt", O_WRONLY|O_CREAT, 0644);
25 | if (fd2 == -1) {
26 | printf("Child fails to open ./test2.txt\n");
27 | exit(1);
28 | }
29 |
30 | write(fd1, "I'm child\n", sizeof("I'm child\n"));
31 | write(fd2, "I'm child\n", sizeof("I'm child\n"));
32 |
33 | close(fd1);
34 | close(fd2);
35 |
36 | exit(0);
37 | }
38 |
39 | // Parent
40 | int fd2 = open("./test2.txt", O_WRONLY|O_CREAT, 0644);
41 | if (fd2 == -1) {
42 | printf("Parent fails to open ./test2.txt\n");
43 | waitpid(child, NULL, 0);
44 | exit(1);
45 | }
46 |
47 | write(fd1, "I'm parent\n", sizeof("I'm parent\n"));
48 | write(fd2, "I'm parent\n", sizeof("I'm parent\n"));
49 |
50 | close(fd1);
51 | close(fd2);
52 |
53 |
54 | waitpid(child, NULL, 0);
55 |
56 | return 0;
57 | }
58 |
--------------------------------------------------------------------------------
/process/README.md:
--------------------------------------------------------------------------------
1 | # 1.child_inherit_flock
2 |
3 | ## 问题
4 |
5 | 当进程退出时,flock可以被自动释放。那么当父进程持有flock并且fork了一个子进程,然后退出。这个flock锁是否还会在父进程推出时释放吗?
6 |
7 | ## Question
8 | The flock could be released automatically when process exits. How about it when parent holds one flock and forks one child then exit? Is the flock released after parent exits?
9 |
10 | ## Answer
11 | No!
12 |
13 | # 2.child_share_flock
14 |
15 | ## 问题
16 |
17 | 既然flock是由父进程和子进程共享,那么父进程持有flock锁并fork一个子进程,这时flock是共享的。那么这时在子进程未退出的情况下,父进程
18 | 释放了锁,然后再次尝试获取这个flock,会怎么样呢?父进程会因为子进程持有锁而阻塞吗?
19 |
20 | ## Question
21 |
22 | The flock is shared between parent and child process. The parent process holds one flock and forks one child process. Now the flock is shared. How about the parent releases the lock and tries to lock it while child is alive ? Is it blocked because child still holds the lock?
23 |
24 | ## Answer
25 |
26 | No !
27 |
28 |
29 | # 3.fork_and_print
30 |
31 | ## 问题
32 |
33 | 一个有关print和fork有趣的问题
34 |
35 | ## Question
36 |
37 | One interesting problem about printf and fork.
38 |
39 | ## Answer
40 |
41 | Please check out the codes in 3.fork_and_print :))
42 |
43 |
44 | # 4.fork_with_fd
45 |
46 | ## 问题
47 | 当父子进程同时往一个文件里写数据是什么样的情况呢?
48 | 情况1:子进程的fd是fork继承下来的;
49 | 情况2:父子进程的fd是fork以后分别打开的;
50 | 这两种情况写入的结果一样的吗?
51 |
52 | ## Question
53 | How about the content when both of parent and child process write the same file?
54 | case1: The child's fd is inherited from parent;
55 | case2: The fd of parent and child is opened after fork;
56 | How about these two cases? Is it same?
57 |
58 | ## Answer
59 |
60 | No. It's totally different!!!
61 |
62 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/signal/1.waitpid_sigchld_ignore/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -Werror -shared -fPIC
9 | LDFLAGS :=
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := waitpid_sigchld_ignore
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/signal/1.waitpid_sigchld_ignore/README.md:
--------------------------------------------------------------------------------
1 | # 描述
2 |
3 | 这个程序将SIGCHLD设置为SIG_IGN,然后fork两个子进程。第一个子进程会sleep 30秒,
4 | 而第二个子进程会直接退出。
5 |
6 | 父进程先waitpid第二个进程,然后再waitpid第一个。
7 |
8 | # Description
9 |
10 | This program sets SIGCHLD as SIG_IGN, and forks two child processes. The first
11 | child sleeps 30 seconds, and second child exits directly.
12 |
13 | The parent process waits the second child firstly, then waits the first.
14 |
15 | # 结论
16 |
17 | 当SIGCHLD被置为SIG_IGN时,waitpid仍然会立刻返回,而不是等待所有子进程终止
18 | 才退出。
19 | 这与"man 2 waitpid"的描述不符。
20 |
21 | # Conclustion
22 | When the SIGCHILD is ignored, the waitpid still return immediately without
23 | waiting all child processes terminate.
24 |
25 | It is oppsite the description of "man 2 waitpid".
26 |
27 | # 原因
28 |
29 | 当使用waitpid等待子进程2时,这里指定了pid。但是由于SIGCHLD是被设置为忽略的,
30 | 所以子进程2退出后,其状态不会保存。
31 | 因此waitpid会因为得不到指定进程的状态而返回错误,No child process,并立刻返回。
32 |
33 | # Reason
34 |
35 | Because when waitpid for child2, we specify the pid. But the SICHLD is ignored,
36 | the exit status of child2 is not saved.
37 | So the waitpid fail to get the child2's status and returns error, and show the reason "No child processes", then
38 | return immediately
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/signal/1.waitpid_sigchld_ignore/waitpid_sigchld_ignore.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | int main(void)
11 | {
12 | pid_t child1, child2;
13 |
14 | printf("Parent is running\n");
15 |
16 | signal(SIGCHLD, SIG_IGN);
17 |
18 |
19 | child1 = fork();
20 | if (child1 == -1) {
21 | printf("Fail to fork child1\n");
22 | exit(1);
23 | } else if (child1 == 0) {
24 | printf("Child1 enter sleep\n");
25 | sleep(30);
26 | printf("Child1 wakes up and exit\n");
27 | exit(0);
28 | }
29 |
30 | printf("Fork child1 successfully\n");
31 | child2 = fork();
32 | if (child2 == -1) {
33 | printf("Fail to fork child2\n");
34 | waitpid(child1, NULL, 0);
35 | exit(1);
36 | } else if (child2 == 0) {
37 | printf("Child2 exit now\n");
38 | exit(0);
39 | }
40 |
41 | printf("Fork child2 successfully, and wait child2\n");
42 | sleep(3);
43 | pid_t ret = waitpid(child2, NULL, 0);
44 | if (ret == -1) {
45 | printf("waitpid child2 return -1, errno(%d): %s\n",
46 | errno, strerror(errno));
47 | }
48 | printf("Wait child1 now\n");
49 | waitpid(child1, NULL, 0);
50 |
51 | printf("Parent exit\n");
52 |
53 | return 0;
54 | }
55 |
--------------------------------------------------------------------------------
/signal/2.waitanypid_sigchld_ignore/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Author Feng Gao
3 | #
4 | #
5 |
6 | .PHONY: all clean depend
7 |
8 | CFLAGS := -Wall -Werror -shared -fPIC
9 | LDFLAGS :=
10 | CC := gcc
11 |
12 | SRCS := $(wildcard *.c)
13 | DEPS := $(patsubst %.c,%.d,$(SRCS))
14 | OBJS := $(patsubst %.c,%.o,$(SRCS))
15 |
16 |
17 | TARGET := waitanypid_sigchld_ignore
18 |
19 | all: $(TARGET)
20 |
21 | $(TARGET): $(OBJS) $(DEPS)
22 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
23 |
24 | %.d:%.c
25 | $(CC) -M $(CFLAGS) $< > $@
26 |
27 | %.o:%.c
28 | $(CC) -c $(CFLAGS) $< -o $@
29 |
30 | explain:
31 | @echo "The information represents in the program:"
32 | @echo "Final executable name: $(PRGM)"
33 | @echo "Source files: $(SRCS)"
34 | @echo "Object files: $(OBJS)"
35 |
36 | depend:$(DEPS)
37 | @echo "Dependencies are now up-to-date"
38 |
39 | clean:
40 | rm -f $(TARGET) $(OBJS) $(DEPS)
41 |
42 | -include $(DEPS)
43 |
--------------------------------------------------------------------------------
/signal/2.waitanypid_sigchld_ignore/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | This program sets SIGCHLD as SIG_IGN, and forks two child processes. The first
4 | child sleeps 30 seconds, and second child exits directly.
5 |
6 | The parent process waits the second child firstly, then waits the first.
7 |
8 | # Conclustion
9 | When the SIGCHLD is set as SIG_IGN, parent invokes waitpid to wait any child process.
10 | The waitpid would block until all childs exit.
11 |
12 | It conforms to the description of "man 2 waitpid".
13 |
14 | # Reason
15 |
16 | Why the result is different with example1?
17 | Because this waitpid is not specified the pid, so it would not return error when
18 | one child process exits. Only when all child processes exit, the waitpid find there
19 | is no child, and return error.
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/signal/2.waitanypid_sigchld_ignore/waitanypid_sigchld_ignore.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | int main(void)
11 | {
12 | pid_t child1, child2;
13 |
14 | printf("Parent is running\n");
15 |
16 | signal(SIGCHLD, SIG_IGN);
17 |
18 |
19 | child1 = fork();
20 | if (child1 == -1) {
21 | printf("Fail to fork child1\n");
22 | exit(1);
23 | } else if (child1 == 0) {
24 | printf("Child1 enter sleep\n");
25 | sleep(30);
26 | printf("Child1 wakes up and exit\n");
27 | exit(0);
28 | }
29 |
30 | printf("Fork child1 successfully\n");
31 | child2 = fork();
32 | if (child2 == -1) {
33 | printf("Fail to fork child2\n");
34 | waitpid(child1, NULL, 0);
35 | exit(1);
36 | } else if (child2 == 0) {
37 | printf("Child2 exit now\n");
38 | exit(0);
39 | }
40 |
41 | printf("Fork child2 successfully, and wait any child\n");
42 | pid_t ret = waitpid(-1, NULL, 0);
43 | if (ret == -1) {
44 | printf("waitpid return -1, errno(%d): %s\n", errno, strerror(errno));
45 | }
46 |
47 | printf("Parent exit\n");
48 |
49 | return 0;
50 | }
51 |
--------------------------------------------------------------------------------
/signal/README.md:
--------------------------------------------------------------------------------
1 | #1. waitpid_sigchld_ignore:
2 |
3 | ## 问题
4 |
5 | 当SIGCHLD被设置为SIG_IGN时,对waitpid有什么影响呢?
6 | 根据"man 2 waitpid"的描述,是否会真的阻塞呢?
7 |
8 | ## Question
9 |
10 |
11 | When SIGCHLD is ignored, how about waitpid?
12 |
13 | The following is from "man 2 waitpid"
14 | /******************************************************************************************************/
15 |
16 |
17 | POSIX.1-2001 specifies that if the disposition of SIGCHLD is set to SIG_IGN or the SA_NOCLDWAIT flag
18 | is set for SIGCHLD (see sigaction(2)), then children that terminate do not become zombies and a call
19 | to wait() or waitpid() will block until all children have terminated, and then fail with errno set to
20 | ECHILD. (The original POSIX standard left the behavior of setting SIGCHLD to SIG_IGN unspecified.
21 | Note that even though the default disposition of SIGCHLD is "ignore", explicitly setting the disposi‐
22 | tion to SIG_IGN results in different treatment of zombie process children.)
23 |
24 | Linux 2.6 conforms to the POSIX requirements. However, Linux 2.4 (and earlier) does not: if a wait()
25 | or waitpid() call is made while SIGCHLD is being ignored, the call behaves just as though SIGCHLD were
26 | not being ignored, that is, the call blocks until the next child terminates and then returns the
27 | process ID and status of that child.
28 |
29 |
30 | /******************************************************************************************************/
31 |
32 | Is it really blocked?
33 |
34 | ## Answer
35 | No!
36 |
37 | # 2.waitanypid_sigchld_ignore
38 |
39 | ## 问题
40 |
41 | 当使用waitpid等待任意pid时,而不是指定pid,又会怎么样呢?
42 | 与问题1会有什么不同吗?是否也会阻塞呢?
43 |
44 | ## Qeustion
45 |
46 | How about wait any pid instead of wait specific pid in case2? Is it different ? Is it block too?
47 |
48 | ## Answer
49 | Yes! This waitpid blocks until all childs exits.
50 |
51 |
52 |
--------------------------------------------------------------------------------