1.使用文件IO函数,拷贝一张图片,父进程拷贝前半部分,子进程拷贝后半部分。不能使用sleep函数。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{ struct stat buf;
int res=stat(argv[1],&buf);
if(res<0)
{
perror("stat");
return -1;
}
off_t size_file=buf.st_size;
pid_t id_1=fork();
if(id_1>0)
{
int fd=open(argv[1],O_RDWR);
int fd1=open(argv[2],O_RDWR|O_CREAT,0777);
if(fd==-1||fd1==-1)
{
perror("open");
return -1;
}
char arr[size_file/2];
read(fd,arr,size_file/2);
write(fd1,arr,size_file/2);
close(fd);
close(fd1);
}
else if(id_1==0)
{
int fd=open(argv[1],O_RDWR);
int fd1=open(argv[2],O_RDWR|O_CREAT,0777);
if(fd==-1||fd1==-1)
{
perror("open");
return -1;
}
char arr[size_file/2];
lseek(fd,size_file/2,SEEK_SET);
lseek(fd1,size_file/2,SEEK_SET);
if(size_file%2==1)
{
size_file=size_file+2;
}
read(fd,arr,size_file/2);
write(fd1,arr,size_file/2);
close(fd);
close(fd1);
}
else
{
perror("fork");
return -1;
}
}
结果:
linux@linux:~/hqyjC基础/IO/day5$ gcc zuoye1.c
linux@linux:~/hqyjC基础/IO/day5$ ./a.out 5.jpg kun.jpg
-rwxrwxr-x 1 linux linux 92461 5月 6 17:47 5.jpg*
-rwxrwxr-x 1 linux linux 92461 5月 6 20:38 kun.jpg*
2. 验证运行到waitpid非阻塞形式时,若子进程没退出,则子进程会不会变成僵尸进程
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
pid_t id_1=fork();
if(id_1>0)
{
waitpid(-1,NULL,WNOHANG);
printf("父进程\n");
printf("id_1=%d\n",id_1);
}
else if(id_1==0)
{
printf("子进程\n");
sleep(3);
printf("子进程退出\n");
exit(0);
}
else
{
perror("fork");
return -1;
}
while(1)
{
sleep(1);
}
return 0;
}
结果:
inux@linux:~/hqyjC基础/IO/day5$ ./a.out
父进程
id_1=3172
子进程
子进程退出
3171 3172 3171 2849 pts/2 3171 Z+ 1000 0:00 [a.
子程序成为了僵尸进程。
3. 创建孤儿进程和僵尸进程
僵尸进程:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
pid_t id_1=fork();
if(id_1>0)
{
printf("id_1=%d\n",id_1);
while(1)
{
sleep(1);
printf("父进程\n");
}
}
else if(id_1==0)
{
printf("子进程\n");
printf("子进程退出\n");
}
else
{
perror("fork");
return -1;
}
return 0;
}
结果:
inux@linux:~/hqyjC基础/IO/day5$ ./a.out
id_1=3287
子进程
子进程退出
父进程
父进程
父进程
3286 3287 3286 2849 pts/2 3286 Z+ 1000 0:00 [a.out] <defunct>
孤儿进程:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
pid_t id_1=fork();
if(id_1>0)
{
printf("id_1=%d\n",id_1);
printf("父进程\n");
printf("父进程退出\n");
}
else if(id_1==0)
{
while(1)
{
sleep(1);
printf("子进程\n");
}
}
else
{
perror("fork");
return -1;
}
return 0;
}
结果:
nux@linux:~/hqyjC基础/IO/day5$ ./a.out
id_1=2218
父进程
父进程退出
linux@linux:~/hqyjC基础/IO/day5$ 子进程
子进程
子进程
子进程
子进程
子进程
子进程
子进程
子进程
子进程
子进程
子进程
子进程
^C
linux@linux:~/hqyjC基础/IO/day5$ 子进程
子进程
子进程
linux@linux:~/hqyjC基础/IO/day5$ 子进程