IO作业 day5 0506

1. 完成拷贝那题

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
	pid_t id=fork();
	if(id>0)
	{
		int fd1,fd2;
		int res;
		fd1=open("./4.PNG",O_RDONLY);
		fd2=open("./5.PNG",O_WRONLY|O_CREAT|O_TRUNC,0664);
		off_t size=lseek(fd1,0,SEEK_END);
		off_t offset=size/2;
		int flag=0;
		char buf[1];
		lseek(fd1,0,SEEK_SET);
		wait(NULL);
		while((res=read(fd1,buf,1))>0&&(flag<size))
		{
			write(fd2,buf,1);
			flag+=res;
		}
	}
	else if(id==0)
	{
		int fd1,fd2;
		int res;
		fd1=open("./4.PNG",O_RDONLY);
		fd2=open("./5.PNG",O_WRONLY|O_CREAT|O_TRUNC,0664);
		off_t size=lseek(fd1,0,SEEK_END);
		char buf[1];
		lseek(fd1,size/2,SEEK_SET);
		while((res=read(fd1,buf,1))>0)
		{
			write(fd2,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() 
{
    pid_t pid = fork();
    if (pid < 0) 
	{
        perror("fork error");
        exit(1);
    }
	else if (pid == 0) 
	{ // 子进程
		printf("pid=%d\n",getpid());
        sleep(10); // 模拟子进程运行的时间
		exit(0);
    } 
	else 
	{ // 父进程
        int status;
        while (1) 
		{
            // 非阻塞等待子进程退出并回收资源
            int ret = waitpid(pid, &status, WNOHANG);
            if (ret == -1) 
			{
                perror("waitpid error");
                exit(1);
            }
        }
    }
    return 0;
}

不会变成僵尸进程
3. 创建孤儿进程和僵尸进程

//创建孤儿进程
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.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(4);
		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 error");
        exit(1);
    }
	else if (pid == 0) 
	{ // 子进程
        exit(0); // 子进程退出,成为僵尸进程
    }
	else 
	{ // 父进程
        sleep(10); // 让父进程暂停 10s
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值