新闻中心

EEPW首页>嵌入式系统>设计应用> 进程间通信之: 信号量

进程间通信之: 信号量

作者: 时间:2013-09-13 来源:网络 收藏

本文引用地址://m.amcfsurvey.com/article/257125.htm

现在我们调用这些简单易用的接口,可以轻松解决控制两个进程之间的执行顺序的同步问题。实现代码如下所示:

/*fork.c*/

#includesys/types.h>

#includeunistd.h>

#includestdio.h>

#includestdlib.h>

#includesys/types.h>

#includesys/ipc.h>

#includesys/shm.h>

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

intmain(void)

{

pid_tresult;

intsem_id;

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

init_sem(sem_id,0);

/*调用fork()函数*/

result=fork();

if(result==-1)

{

perror(Forkn);

}

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

{

printf(Childprocesswillwaitforsomeseconds...n);

sleep(DELAY_TIME);

printf(Thereturnedvalueis%dinthechildprocess(PID=%d)n,

result,getpid());

sem_v(sem_id);

}

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

{

sem_p(sem_id);

printf(Thereturnedvalueis%dinthefatherprocess(PID=%d)n,

result,getpid());

sem_v(sem_id);

del_sem(sem_id);

}

exit(0);

}

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

$./simple_fork

Childprocesswillwaitforsomeseconds…/*子进程在运行中*/

Thereturnedvalueis4185inthefatherprocess(PID=4184)/*父进程先结束*/

[…]$Thereturnedvalueis0inthechildprocess(PID=4185)/*子进程后结束了*/

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

$./sem_fork

Childprocesswillwaitforsomeseconds…

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

Thereturnedvalueis0inthechildprocess(PID=4185)/*子进程结束了*/

Thereturnedvalueis4185inthefatherprocess(PID=4184)/*父进程结束*/

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

linux操作系统文章专题:linux操作系统详解(linux不再难懂)

数字通信相关文章:数字通信原理



上一页 1 2 3 下一页

评论


相关推荐

技术专区

关闭