1.使用文件IO函数,拷贝一张图片,父进程拷贝前半部分,子进程拷贝后半部分。不能使用sleep函数。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAXSIZE 300
int main(int argc, const char *argv[])
{
pid_t cpid=fork();
if(cpid>0)
{
int fd,fd1;
int res;
fd=open("picture.jpg",O_RDONLY);
if(fd<0)
{
perror("open");
return -1;
}
fd1=open("copy_pic.jpg",O_WRONLY|O_CREAT|O_TRUNC,0666);
if(fd1<0)
{
perror("fd1open");
return -1;
}
off_t len=lseek(fd,0,SEEK_END);
off_t offset=len/2;
int flag=0;
char buf[1];
lseek(fd,0,SEEK_SET);
wait(NULL);
while((res=read(fd,buf,1))>0 && (flag<len))
{
write(fd1,buf,1);
flag+=res;
}
}
else if(cpid==0)
{
int fd,fd1;
int res;
fd=open("picture.jpg",O_RDONLY);
if(fd<0)
{
perror("fdopen");
return -1;
}
fd1=open("copy_pic.jpg",O_WRONLY|O_CREAT|O_TRUNC,0666);
if(fd1<0)
{
perror("open");
return -1;
}
off_t len=lseek(fd,0,SEEK_END);
char buf[1];
lseek(fd,len/2,SEEK_SET);
while((res=read(fd,buf,1))>0)
{
write(fd1,buf,1);
}
}
return 0;
}
结果
2. 验证运行到waitpid非阻塞形式时,若子进程没退出,则子进程会不会变成僵尸进程
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc,int *argv[])
{
cpid_t cpid = fork();
if (cpid == 0)
{
printf("cpid=%d\n",getcpid());
sleep(99);
exit(0);
}
else if(cpid>0)
{
int status;
while (1)
{
int res = waitpid(cpid, &status, WNOHANG);
if (res == -1)
{
perror("error");
exit(1);
}
}
}
return 0;
}
结果
3. 创建孤儿进程和僵尸进程
//创建孤儿进程
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t cpid=fork();
if(cpid>0)
{
printf("pid=%d. My child's pid is %d\n",getpid(),cpid);
exit(0);
}
else if(0==cpid)
{
sleep(5);
printf("parent pid =%d,my pid=%d\n",getppid(),getpid());
}
return 0;
}
//创建僵尸进程
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid = fork();
if (pid < 0)
{
perror("fork");
return -1;
}
else if (pid == 0)
{
exit(0); // 成为僵尸进程
}
else
{
sleep(5);
}
return 0;
}