1.使用文件IO函数,拷贝一张图片,父进程拷贝前半部分,子进程拷贝后半部分。不能使用sleep函数。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int fd_r = open("./1.png", O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
int fd_w = open("./copy.png", O_WRONLY | O_CREAT | O_TRUNC, 0755);
if(fd_w < 0)
{
perror("open");
return -1;
}
off_t filesize = lseek(fd_r, 0 ,SEEK_END); //计算文件大小
lseek(fd_r, 0, SEEK_SET); //重新偏移到开头
char c = 0;
long i = 0;
while(i < filesize/2)
{
read(fd_r, &c, 1);
write(fd_w, &c, 1);
i++;
}
pid_t cpid = fork();
if(cpid == 0)
{
while(1)
{
ssize_t res = read(fd_r, &c, 1);
if(res == 0)
break;
write(fd_w, &c ,1);
}
}
else if(cpid == -1)
{
perror("fork");
return -1;
}
return 0;
}
2.父进程以非阻塞形式运行到waitpid时,若子进程没退出,则子进程会不会变成僵尸进程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t cpid = fork();
if(cpid > 0)
{
printf("parent pid=%d\n",getpid());
int wstatus = 0;
waitpid(-1, &wstatus, WNOHANG);
//waitpid(-1, &wstatus, 0);
printf("%d\n", (wstatus&0xff00)>>8);
}
else if(cpid == 0)
{
printf("child pid=%d\n",getpid());
sleep(5);
printf("子进程准备退出\n");
exit(0);
}
else
{
perror("fork");
return -1;
}
while(1)
sleep(1);
return 0;
}
子进程会变成僵尸进程;
3.创建孤儿进程和僵尸进程
孤儿进程:父进程退出,子进程还在运行
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t cpid = fork();
if(cpid > 0)
{
printf("父进程 pid=%d\n", getpid());
exit(0);
}
else if(cpid == 0)
{
sleep(1);
printf("子进程 pid=%d ppid=%d\n", getpid(), getppid());
}
else
{
perror("fork");
return -1;
}
while(1)
sleep(1);
return 0;
}
僵尸进程:子进程退出,父进程没有收尸
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t cpid = fork();
if(cpid > 0)
{
printf("parent pid=%d\n", getpid());
}
else if(cpid == 0)
{
printf("child pid=%d\n", getpid());
exit(0);
}
else
{
perror("fork");
return -1;
}
while(1)
sleep(1);
return 0;
}