blob: f248afe7668bcf26e6c63d245a8ebc2b9d1a6a1a [file] [log] [blame]
Lucas Eckels9bd90e62012-08-06 15:07:02 -07001/*****************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 *
9 * This is a very simple example using the multi interface.
10 */
11
12#include <stdio.h>
13#include <string.h>
14
15/* somewhat unix-specific */
16#include <sys/time.h>
17#include <unistd.h>
18
19/* curl stuff */
20#include <curl/curl.h>
21
22/*
23 * Simply download a HTTP file.
24 */
25int main(int argc, char **argv)
26{
27 CURL *http_handle;
28 CURLM *multi_handle;
29
30 int still_running; /* keep number of running handles */
31
32 http_handle = curl_easy_init();
33
34 /* set the options (I left out a few, you'll get the point anyway) */
35 curl_easy_setopt(http_handle, CURLOPT_URL, "http://www.example.com/");
36
37 /* init a multi stack */
38 multi_handle = curl_multi_init();
39
40 /* add the individual transfers */
41 curl_multi_add_handle(multi_handle, http_handle);
42
43 /* we start some action by calling perform right away */
44 curl_multi_perform(multi_handle, &still_running);
45
46 while(still_running) {
47 struct timeval timeout;
48 int rc; /* select() return code */
49
50 fd_set fdread;
51 fd_set fdwrite;
52 fd_set fdexcep;
53 int maxfd = -1;
54
55 long curl_timeo = -1;
56
57 FD_ZERO(&fdread);
58 FD_ZERO(&fdwrite);
59 FD_ZERO(&fdexcep);
60
61 /* set a suitable timeout to play around with */
62 timeout.tv_sec = 1;
63 timeout.tv_usec = 0;
64
65 curl_multi_timeout(multi_handle, &curl_timeo);
66 if(curl_timeo >= 0) {
67 timeout.tv_sec = curl_timeo / 1000;
68 if(timeout.tv_sec > 1)
69 timeout.tv_sec = 1;
70 else
71 timeout.tv_usec = (curl_timeo % 1000) * 1000;
72 }
73
74 /* get file descriptors from the transfers */
75 curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
76
77 /* In a real-world program you OF COURSE check the return code of the
78 function calls. On success, the value of maxfd is guaranteed to be
79 greater or equal than -1. We call select(maxfd + 1, ...), specially in
80 case of (maxfd == -1), we call select(0, ...), which is basically equal
81 to sleep. */
82
83 rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
84
85 switch(rc) {
86 case -1:
87 /* select error */
88 still_running = 0;
89 printf("select() returns error, this is badness\n");
90 break;
91 case 0:
92 default:
93 /* timeout or readable/writable sockets */
94 curl_multi_perform(multi_handle, &still_running);
95 break;
96 }
97 }
98
99 curl_multi_cleanup(multi_handle);
100
101 curl_easy_cleanup(http_handle);
102
103 return 0;
104}