IO进程线程作业

本文提供了孤儿进程、僵尸进程和守护进程的C语言实现示例,并展示了如何通过代码创建这些不同类型的进程。孤儿进程通过无限循环模拟;僵尸进程通过子进程直接退出而父进程未等待产生;守护进程则通过改变会话ID等方式实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

孤儿进程

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
	pid_t pid = fork();//创建子进程
	//创建孤儿进程
	if(pid>0)
	{
		//父进程代码区
	}
	else if(pid==0)
	{
		//子进程代码区
		while(1)
		{};
	}
	else
	{
		perror("fork");
		return -1;
	}
	return 0;
}

僵尸进程

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, const char *argv[])
{
	pid_t pid = fork();//创建子进程
	//创建僵尸进程
	if(pid>0)
	{
		//父进程代码区
		while(1)
		{
			printf("this is parent\n");
			sleep(1);
		}
	}
	else if(pid==0)
	{
		//子进程代码区
		exit(0);
		//直接退出
	}
	else
	{
		perror("fork");
		return -1;
	}
	return 0;
}

守护进程

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>

int main(int argc, const char *argv[])
{
	pid_t pid = fork();//创建子进程
	//创建守护进程
	if(pid>0)
	{
		//父进程代码区
	}
	else if(pid==0)
	{
		//子进程代码区
		//创建新的会话组
		pid_t sid=setsid();

		//修改允许目录到不可卸载的文件目录
		chdir("/");

		//关闭所有文件描述符
		for(int i=0;i<1024;i++)
			close(i);
		while(1)
		{
			//功能代码
			sleep(1);
		}
	}
	else
	{
		perror("fork");
		return -1;
	}
	return 0;
}

打印时间

#include <stdio.h>
#include <sys/types.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>

void *ttime(void *arg)
{
	FILE *fp=fopen("time.txt","a+");
	int count=1;
	int a;
	while((a=fgetc(fp))!=-1)
	{
		if(a=='\n'){
			count++;
		}
	}
	while(1)
	{
		size_t t=time(NULL);
		struct tm *tm=localtime(&t);
		fprintf(fp,"[%d] %02d-%02d-%02d %02d:%02d:%02d\n",
				count,tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,\
				tm->tm_hour,tm->tm_min,tm->tm_sec);
		fflush(fp);
		count++;
		sleep(1);
	}
	fclose(fp);
	return 0;

}

int main(int argc, const char *argv[])
{
	pthread_t tpid;
	if(pthread_create(&tpid,NULL,ttime,NULL))
	{
		perror("pthread_cread:");
		return 0;
	}
	char c;
	while(1)
	{
		c=fgetc(stdin);
		if(c=='q')
		{
			break;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值