命名管道的使用

        我在工作中碰到了一個這樣的問題,有兩個程序,第一個程序會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);
}
發佈了34 篇原創文章 · 獲贊 1 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章