- 论坛徽章:
- 0
|
下面是我用FIFO写的子进程间通信的程序,主要实现先创建子进程1,执行完之后发信号给父进程,父进程再创建子进程2,然后实现2者之间的通信。但运行结果是could not open fifo,这是为什么呢?是不是子进程1结束了,就不能实现通信啦?请问错在哪里?
- #include<stdio.h>;
- #include<stdlib.h>;
- #include<fcntl.h>;
- #include<sys/types.h>;
- #include<sys/stat.h>;
- #include<limits.h>;
- #include<unistd.h>;
- #include"err_exit.h"
- #define FIFO_FILE "myfifo"
-
- static pid_t child_id[1];
- static int myfifo1(void);
- static int myfifo2(void);
- static int fifo_fd,n;
- static char buffer[BUFSIZ+1];
- static char some_data[]="hello,world!";
- void sig_usr(int signo)/*信号SIGUSR1的句柄*/
- {
-
- printf("received SIGUSR1 \n");
- /*创建新的子进程2*/
- child_id[1]=fork();
- if(child_id[1]==0)
- {
- /*自己定义的进程通信函数*/
- myfifo1();
- myfifo2();
- /*子进程2的功能*/
- child_function2();
-
- exit(0);
- }
- else if(child_id[1]<0)
- printf("fork error.");
- }
- /*子进程执行此函数*/
- int child_function1()
- {
- printf("this is child1:\n");
- printf("done1.\n");
- /*发出信号通知父进程子进程1已完成*/
- kill(getppid(),SIGUSR1);
- exit(EXIT_SUCCESS);
- return 0;
- }
- int child_function2()
- {
- printf("this is child2:\n");
- printf("Done2.\n");
- exit(EXIT_SUCCESS);
- return 0;
- }
- int main(int argc, char *argv[])
- {
-
- int i;
- int status;
- struct sigaction usr_action;
- sigset_t block_mask;
- /*初始化信号句柄*/
- sigfillset(&block_mask);
- usr_action.sa_handler=sig_usr;/*指定与信号相关连的动作*/
- usr_action.sa_mask=block_mask;
- usr_action.sa_flags=0;
- /*为信号SIGUSR1*/
- sigaction(SIGUSR1,&usr_action,NULL);
-
-
- /*创建子进程1*/
- child_id[0]=fork();
- if(child_id[0]==0)
- { child_function1();
- exit(0); }
- else if(child_id[0]<0)
- printf("fork error.");
-
- /*父进程*/
- for(i=0;i<2;i++)
- waitpid(child_id[i],&status,0);
- printf("data sending is over.\n");
- exit(EXIT_SUCCESS);
- }
- int myfifo2(void)
- {
-
- if(access(FIFO_FILE,F_OK)==-1)
- { if(mkfifo(FIFO_FILE,0666)!=0)
- {
- printf("could not create fifo %s\n",FIFO_FILE);
- exit(EXIT_FAILURE);
- }
- }
- if((fifo_fd=open(FIFO_FILE,O_RDONLY))<0)
- {
- printf("could not open fifo %s\n",FIFO_FILE);
- exit(EXIT_FAILURE);
- }
- printf("child2 %d opened:%s\n",getpid(),FIFO_FILE);
- while((n=read(fifo_fd,buffer,BUFSIZ))>;0)
- printf("child2 %d received %d bytes:%s\n",getpid(),n,buffer);
- close(fifo_fd);
- printf("child2 %d received %d bytes then finished\n",getpid(),n);
- return 0;
- }
- int myfifo1(void)
- {
- int fifo_fd,n;
- char buffer[BUFSIZ+1];
- char some_data[]="hello,world!";
- if((fifo_fd=open(FIFO_FILE,O_WRONLY))<0)
- {
- printf("could not open fifo %s\n",FIFO_FILE);
- exit(EXIT_FAILURE);
- }
- printf("child1 %d opened:%s\n",getpid(),FIFO_FILE);
- if(n=write(fifo_fd,some_data,strlen(some_data))==-1)
- err_exit("FIFO broken");
- printf("child1 %d write %d bytes\n",getpid(),n);
- close(fifo_fd);
- printf("child1 %d write %d bytes then finished\n",getpid(),n);
- return 0;
- }
-
-
复制代码 |
|