并发小程序

02fock.c 

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

int main()
{
	printf("Hello,Process!\n");
	pid_t pid = fork();
	if(pid == -1)//错误处理
	{
		perror("fork failed");
		return 0;
	}
	else if(pid > 0)
	{
		//这是父进程要做的事情
		//fork给父进程返回子进程的ID
		printf("这是父进程,我的ID是%d\n",getpid());
		printf("这是父进程,我的父进程的ID是%d\n",getppid());
		printf("这是父进程,我的子进程的ID是%d\n",pid);
	}
	else if(pid == 0)
	{
		//这是子进程要做的事情
		printf("这是子进程,我的ID是%d\n",getpid());
		printf("这是子进程,我的父进程的ID是%d\n",getppid());
	}
	printf("Goodbye,Process!\n");
	
	return 0;
}

03fock.c

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

int sum(int a,int b)
{
	//return a + b;
	exit(a+b);
}

int main()
{
	fork();
	sum(5,3);
	printf("Hello,Process!\n");
	return 0;
}

head.h

#ifndef __HEAD_H__
#define __HEAD_H__

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <semaphore.h>

#endif

 

04exit.c

#include "head.h"

int main()
{
	pid_t pid = fork();
	if(pid == -1)
	{

	}
	else if(pid > 0)
	{
		printf("这是父进程,hello!\n");
		sleep(30);
	}
	else
	{
		printf("这是子进程,我嗝屁了!\n");
		exit(0);
	}
}

05.c

#include "head.h"

int main()
{
	pid_t pid = fork();
	if(pid == -1)
	{

	}
	else if(pid == 0)//子进程
	{
		printf("这是子进程,子进程ID:%d\n",getpid());
		printf("这是子进程,父进程ID:%d\n",getppid());
		//return 260;
		exit(250);
	}	
	else//父进程
	{
		printf("这是父进程,父进程ID为:%d\n",getpid());
		int sta;
		pid_t pid1 = waitpid(pid,&sta,0);
		if(WIFEXITED(sta))
		{
			printf("sta = %d\n",sta);
			printf("退出进程的ID:%d,退出码为%d\n",pid1,WEXITSTATUS(sta));
		}
	}
}

06.c

#include "head.h"

//自定义的中断服务处理函数
void my_sig_handler(int sig)
{
	printf("xixi,你咋嗝屁了!\n");
	wait(NULL);
}

int main()
{
	signal(SIGCHLD,my_sig_handler);
	pid_t pid = fork();
	if(pid == -1)
	{

	}
	else if(pid == 0)
	{
		printf("这是子进程,我马上要嗝屁了!\n");
		sleep(3);
		exit(0);
	}
	else
	{
		while(1)
			;
	}
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值