1>
源代码:
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid = -1;
FILE *src = NULL;
FILE *dest = NULL;
if ((src = fopen("./base.txt", "r")) == NULL)
{
perror("fopen error");
return -1;
}
fseek(src, 0, SEEK_END);
fseek(src, 0, SEEK_SET);
char buf1[64] = "";
char buf2[64] = "";
int size = ftell(src);
//创建一个子进程
pid = fork();
//判断父子进程执行的程序代码
if (pid > 0)
{
int i = 0;
printf("我是父进程,当前进程id号:%d,ppid=%d, childid=%d\n", getpid(),
getppid(), pid);
if ((dest = fopen("./aim1.txt", "w")) == NULL)
{
perror("fopen error");
return -1;
}
while ((fgets(buf1, sizeof(buf1) - 1, src)) != NULL && i++ <= size / 2)
{
fputs(buf1, dest);
}
}
else
{
int j = size / 2;
fseek(dest,size/2,SEEK_END);
printf("我是子进程当前进程id号:%d,ppid = %d\n", getpid(), getppid());
if ((dest = fopen("./aim2.txt", "w")) == NULL)
{
perror("fopen error");
return -1;
}
fseek(src, size / 2, SEEK_SET);
while ((fgets(buf2, sizeof(buf2) - 1, src)) != NULL && j++ <= size)
{
fputs(buf2, dest);
}
}
wait(NULL); //阻塞等待子进程结束
printf("已经成功回收子进程\n");
fclose(src);
fclose(dest);
return 0;
}
效果图: