现在的位置: 首页 > 综合 > 正文

关于进程间通信

2013年05月03日 ⁄ 综合 ⁄ 共 1239字 ⁄ 字号 评论关闭

简要记录一下今天遇到的问题和解决方法
主函数需要创建一个监听网络端口的守护进程,并将监听到的数据传递给主函数,用于显示。其中,主函数有Qt实现,因此需要采用多线程来维护显示界面,即用一个线程维护显示界面,另一个线程负责向界面上添加数据。(坦白说,我觉得肯定有很简单的方法就能够实现显示数据,不过,由于图形界面不是我负责,自己又不会Qt,没办法了~~研究中)
现在的问题是,守护进程如何将监听到的数据传递给父进程中负责显示的线程?很显然,不能采用函数返回值,守护进程要是能返回,也就不叫守护进程了,也不能用全局变量,因为父子进程不共享全局变量。翻了半天书,发现可以用IPC,尝试了最简单的管道,找到一种很笨的方法。
下面是一个简单的例子
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#define MAXLINE    1024
int fd[2];
pthread_t pthid;
void* getMsg(void* arg)//父进程中负责显示的线程函数
{
    char buff[MAXLINE];
    int n;
    close(fd[1]); //关闭写管道
    while(1)
    {
    n=read(fd[0],buff,MAXLINE);//从管道中读取数据
    buff[n]='/0';
    printf("%s/n",buff);//实际应用中要用Qt实现~
    }

}
int main(void)
{
    int        n;
    int        err;
    pid_t    pid;
    char    line[MAXLINE];

    if(pipe(fd)<0)
    {
    fprintf(stderr, "pipe error/n");
    return -1;
    }
    if((pid=fork())<0)
    {
    fprintf(stderr,"fork error/n");
    return -1;
    }
    else if(pid=0)//子进程
    {
    while(1)
    {
        close(fd[0]);//关闭读管道
        write(fd[1],"hello/n",sizeof("hello/n"));//向管道中写数据
        sleep(1);
    }
    }
    else
    {
    err=pthread_create(&pthid,NULL,getMsg,NULL);//创建线程
    if(err!=0)
    {
        fprintf(stderr,"can't create thread/n");
        exit(1);
    }
    while(1)
    {
        printf("this is main thread/n");
        sleep(1);
    }
    }
    return 0;
}

感觉这个办法非常笨?但又找不到更好的~发愁中……

抱歉!评论已关闭.