2023.05.06 IO进程线程DAY5

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值