题目
1> 使用父子进程完成两个文件的拷贝,父进程拷贝前一半内容,子进程拷贝后一半内容,子进程结束后退出,父进程回收子进程的资源
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s srcfile destfile\n", argv[0]);
return EXIT_FAILURE;
}
FILE *sfp = fopen(argv[1], "r");
if (!sfp)
{
perror("Failed to open source file");
return EXIT_FAILURE;
}
FILE *dfp = fopen(argv[2], "w");
if (!dfp)
{
perror("Failed to open destination file");
fclose(sfp);
return EXIT_FAILURE;
}
// 计算行数
int count = 0;
char c;
while ((c = fgetc(sfp)) != EOF)
{
if (c == '\n')
count++;
}
rewind(sfp); // 重置文件指针
pid_t pid = fork();
if (pid < 0)
{
perror("Failed to fork");
fclose(sfp);
fclose(dfp);
return EXIT_FAILURE;
}
if (pid > 0)
{
// 父进程
char buf[1024];
int line_count = 0;
while (fgets(buf, sizeof(buf), sfp) && line_count < count / 2)
{
fputs(buf, dfp);
line_count++;
}
fclose(dfp);
// 等待子进程结束
wait(NULL);
printf("复制成功\n");
fclose(dfp);
fclose(sfp);
}
else if (pid == 0)
{
FILE *dfp = fopen(argv[2], "a");
if (!dfp)
{
perror("Failed to open destination file");
fclose(sfp);
return EXIT_FAILURE;
}
// 子进程
char discard_buf[1024];
for (int i = 0; i < count / 2; i++)
{
if (!fgets(discard_buf, sizeof(discard_buf), sfp))
break;
}
_exit(EXIT_SUCCESS);
}
return 0;
}