命名管道的使用

博主在工作中遇到程序调用问题,第一个程序fork进程exec调用第二个程序后,要求第一个程序父进程停止运行,直到第二个程序退出或到特定时刻再继续。文中给出了gui和player两个示例程序的代码,展示如何实现该功能。

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

        我在工作中碰到了一个这样的问题,有两个程序,第一个程序会fork一个进程exec调用第二个程序,这样调用后,第一个程序还是继续执行父进程的。我要求第一个程序的父进程停止运行,直到第二个程序退出或运行到某个时候才继续运行。
下面是两个例子程序的代码
先运行gui程序,再运行player程序

./gui&在后台运行
./player


/*gui.c*/
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_SERVER "./fifoserver"
int main()
{
 int fd;
 char buf;
 printf("GUI:Create Name Pipe/n");
 umask(0);
 //if(mkfifo(FIFO_SERVER,O_CREAT|O_EXCL))
 if(mkfifo(FIFO_SERVER,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP))
 {
  printf("cannot create fifoserver/n");
 }
 printf("GUI:Open NamePipe .../n");
 //=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);
 fd=open(FIFO_SERVER,O_RDWR,0);
 //fd=open(FIFO_SERVER,O_RDONLY,0);
 if(fd==-1)
 {
  printf("GUI:Open error/n");
  return 0; 
 }
 printf("GUI:Wait NamePipe Write.../n");
 read(fd,(char *)(&buf),1); //程序会在这里停止,直到运行player程序
 printf("GUI:player finished!/n");
 unlink(FIFO_SERVER);
}


/*player.c*/
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_SERVER "./fifoserver"
int main()
{
 int fd;
 fd=open(FIFO_SERVER,O_WRONLY,0);
 if(fd==-1)
 {
  printf("open for read error/n");
  return 0; 
 }
 write(fd,(char *)"OVER",5);//数据写入命名管道后,gui继续运行
 close(fd);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值