IO-day5

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值