微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > 进程间通信之: 信号量

进程间通信之: 信号量

时间:08-13 来源:3721RD 点击:

#include <sys/types.h>de <sys/types.h>

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#define DELAY_TIME 3 /* 为了突出演示效果,等待几秒钟,*/

int main(void)

{

pid_t result;

int sem_id;

sem_id = semget(ftok(".", 'a'), 1, 0666|IPC_CREAT); /* 创建一个信号量*/

init_sem(sem_id, 0);

/*调用fork()函数*/

result = fork();

if(result == -1)

{

perror("Fork\n");

}

else if (result == 0) /*返回值为0代表子进程*/

{

printf("Child process will wait for some seconds...\n");

sleep(DELAY_TIME);

printf("The returned value is %d in the child process(PID = %d)\n",

result, getpid());

sem_v(sem_id);

}

else /*返回值大于0代表父进程*/

{

sem_p(sem_id);

printf("The returned value is %d in the father process(PID = %d)\n",

result, getpid());

sem_v(sem_id);

del_sem(sem_id);

}

exit(0);

}

读者可以先从该程序中删除掉信号量相关的代码部分并观察运行结果。

$ ./simple_fork

Child process will wait for some seconds… /*子进程在运行中*/

The returned value is 4185 in the father process(PID = 4184)/*父进程先结束*/

[…]$ The returned value is 0 in the child process(PID = 4185) /* 子进程后结束了*/

再添加信号量的控制部分并运行结果。

$ ./sem_fork

Child process will wait for some seconds…

/*子进程在运行中,父进程在等待子进程结束*/

The returned value is 0 in the child process(PID = 4185) /* 子进程结束了*/

The returned value is 4185 in the father process(PID = 4184) /* 父进程结束*/

本实例说明使用信号量怎么解决多进程之间存在的同步问题。我们将在后面讲述的共享内存和消息队列的实例中,看到使用信号量实现多进程之间的互斥。

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top