编制实现管道通信的程序。

1、编制实现管道通信的程序。
使用系统调用 pipe()函数建立一条管道线,两个子进程分别向管道各写一句话。
Child process 1 is sending a message!
Child process 2 is sending a message!
而父进程则从管道中读出来自于两个子进程的信息,显示在屏幕上。
要求∶父进程先接收子进程P1发来的消息,然后再接收子进程 P2发来的消息

要点:1.需要创建三个进程,一个父进程两个子进程
2.可以通过控制信号量来控制先执行进程P1,再执行进程P2.1
2
3
其中信号量P,V设置如下:

int init_sem(int sem_id, int n,int init_value)
{
	union semun{
		int val;
		struct semid_ds *buf;
		unsigned short *array;
	};
	union semun sem_union;
	sem_union.val = init_value;   
	if(semctl(sem_id, n, SETVAL, sem_union) == -1)
	{
		perror("Initialize semaphore");
		return -1;
	}
	return 0;

}

int del_sem(int sem_id)
{

	if (semctl(sem_id, 0, IPC_RMID,NULL) == -1)
	{

		perror("Delete semaphore");
		return -1;
	}
}


int sem_p(int sem_id,int n)
{
	struct sembuf sem_b;
	sem_b.sem_num = n; 
	sem_b.sem_op = -1; 
	sem_b.sem_flg = SEM_UNDO;
	if (semop(sem_id, &sem_b, 1) == -1)
	{
		perror("P operation");

		return -1;
	}
	return 0;
}


int sem_v(int sem_id,int n)
{
	struct sembuf sem_b;
	sem_b.sem_num = n; 
	sem_b.sem_op = 1; 
	sem_b.sem_flg = SEM_UNDO;
	if (semop(sem_id, &sem_b, 1) == -1)
	{
		perror("V operation");
	return -1;
	}
	return 0;
}
  • 2
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hello&&world

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值