75 lines
1.9 KiB
C
75 lines
1.9 KiB
C
/*
|
||
编写一个程序, 由主线程从键盘接收输入的网址(如http://www.baidu.com), 由子线程完成网址的下载并写入到tmpN.html临时文件中, 并在子线程中打印输出结果.输入exit时, 退出程序.
|
||
【提示】基于execlp()函数执行`curl 网址 > tmp1.html`, 其中N是第几次请求.
|
||
*/
|
||
#include <stdio.h>
|
||
#include <pthread.h>
|
||
#include <unistd.h>
|
||
#include <string.h>
|
||
#include <stdlib.h>
|
||
|
||
typedef struct url_info_s
|
||
{
|
||
char *url;
|
||
int N;
|
||
} URL_INFO;
|
||
|
||
void *download(void *data)
|
||
{
|
||
URL_INFO *info = (URL_INFO *)data;
|
||
char end_name[20];
|
||
sprintf(end_name, "tmp%d.html", info->N);
|
||
// execlp("curl", "curl", info->url, "-o", end_name, NULL);
|
||
// 注意:这里使用 "-o" 参数指定输出文件名
|
||
char command[200];
|
||
sprintf(command, "curl %s -o %s", info->url, end_name);
|
||
system(command);
|
||
|
||
sprintf(command, "cat %s", end_name);
|
||
system(command);
|
||
|
||
return NULL;
|
||
}
|
||
|
||
// void *view(void *data)
|
||
// {
|
||
// URL_INFO *info = (URL_INFO *)data;
|
||
// char end_name[20];
|
||
// sprintf(end_name, "tmp%d.html", info->N);
|
||
// execlp("cat", "cat", end_name, NULL);
|
||
// // 使用 execlp 调用 cat 命令打印输出结果
|
||
|
||
// return NULL;
|
||
// }
|
||
|
||
int main()
|
||
{
|
||
int n = 1; // 初始化 n 的值为 1
|
||
char buf[100];
|
||
|
||
while (1)
|
||
{
|
||
printf("请输入网址(输入exit退出):");
|
||
fgets(buf, sizeof(buf), stdin);
|
||
buf[strlen(buf) - 1] = '\0';
|
||
if (strcmp(buf, "exit") == 0)
|
||
{
|
||
break;
|
||
}
|
||
|
||
URL_INFO urls;
|
||
urls.url = buf;
|
||
urls.N = n++;
|
||
|
||
pthread_t download_tid, view_tid;
|
||
pthread_create(&download_tid, NULL, download, &urls);
|
||
pthread_join(download_tid, NULL);
|
||
|
||
// pthread_create(&view_tid, NULL, view, &urls);
|
||
// pthread_join(view_tid, NULL);
|
||
}
|
||
|
||
printf("---over---\n");
|
||
return 0;
|
||
}
|