系統(tǒng)與網(wǎng)絡編程(進程間通信)

進程間通信

  • ipc:interprocess communication

通信方式

  1. 管道通信


    Paste_Image.png
    • 無名管道:通過pipe創(chuàng)建出來的管道,只能在父子進程或子進程間使用,創(chuàng)建該管道的進程一旦結(jié)束,則該無名管道也會銷毀
      • 父進程輸出關閉子進程的輸出,打開輸入。子進程輸出關閉父進程的輸出,打開輸入。
    • 父進程與子進程之間的通信
    #include <unistd.h>//pipe
    #include <stdio.h>
    #include <string.h>
    //通過pipe創(chuàng)建的管道屬于無名管道
    //只能在父子進程或子進程間使用
    //創(chuàng)建該管道的進程一旦結(jié)束,則該無名管道也會銷毀
    int main()
    {
        int pipefd[2]={-1};//管道文件描述符
        int ret=-1;
        ret=pipe(pipefd);//創(chuàng)建的管道是位于內(nèi)核空間的,管道兩端的描述符存儲到pipe數(shù)組
                        //pipefd[0]表示數(shù)據(jù)流出段,可以從此端讀取數(shù)據(jù)
                        //pipefd[1]表示數(shù)據(jù)進入段,可以從此端寫入數(shù)據(jù)
        if(ret==-1)//創(chuàng)建管道失敗
        {
            perror("pipe");
            return -1;
        }
        //創(chuàng)建一個進程
        pid_t pid=-1;
        //管道的創(chuàng)建是創(chuàng)建在內(nèi)核中,不屬于獨立進程
        //fork產(chǎn)生的子進程是不會再創(chuàng)建一個管道
        //只是對管道文件進行了一次拷貝
        pid=fork();
        if(pid>0)//parent
        {
            int iSign=0;
            char caBuf[32]={'\0'};
            while(1)
            {
                memset(caBuf,'\0',sizeof(caBuf));
                if(iSign==0)
                {
                    printf("parent input data\n");
                    scanf("%s",caBuf);
                    write(pipefd[1],caBuf,sizeof(caBuf));
                    iSign=1;
                    sleep(1);
                }
                else if(iSign==1)
                {
                    read(pipefd[0],caBuf,sizeof(caBuf));
                    printf("child says:%s\n",caBuf);
                    iSign=0;
                }
            }
        }
        else if(pid==0)//child
        {
            int iSign=1;
            char caBuf[64]={'\0'};
            while(1)
            {
                memset(caBuf,'\0',sizeof(caBuf));
                if(iSign==1)
                {
                    read(pipefd[0],caBuf,sizeof(caBuf));
                    printf("parent says:%s\n",caBuf);
                    iSign=0;
                }
                else if(iSign==0)
                {
                    printf("child input data\n");
                    scanf("%s",caBuf);
                    write(pipefd[1],caBuf,sizeof(caBuf));
                    iSign=1;
                    sleep(1);
                }
            }
        }
        else if(pid==-1)//fork failed
        {
            perror("fork");
            return -1;
        }
        return 0;
    }
    
    • 子進程與子進程之間的通信
    #include <stdio.h>
    #include <unistd.h>
    #include <string.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    int main()
    {
        int pipefd[2]={0};
        int ret=-1;
        ret=pipe(pipefd);
        if(ret==-1)
        {
            perror("pipe");
            return -1;
        }
    
        pid_t pid=fork();
        if(pid>0)
        {
            pid_t pid2=fork();
            if(pid2>0)
            {
                waitpid(pid,NULL,0);
                waitpid(pid2,NULL,0);
            }
            else if(pid2==0)
            {
                int iSign=1;
                char caBuf[64]={'\0'};
                while(1)
                {
                    memset(caBuf,'\0',sizeof(caBuf));
                    if(iSign==1)
                    {
                        read(pipefd[0],caBuf,sizeof(caBuf));
                        printf("child2 says:%s\n",caBuf);
                        iSign=0;
                    }
                    else if(iSign==0)
                    {
                        printf("child1 input data\n");
                        scanf("%s",caBuf);
                        write(pipefd[1],caBuf,sizeof(caBuf));
                        iSign=1;
                        sleep(1);
                    }
                }
            }
            else if(pid2==-1)
            {
                perror("first fork");
                return -1;
            }
        }
        else if(pid==0)
        {
            int iSign=0;
            char caBuf[64]={'\0'};
            while(1)
            {
                memset(caBuf,'\0',sizeof(caBuf));
                if(iSign==0)
                {
                    printf("child2 input data\n");
                    scanf("%s",caBuf);
                    write(pipefd[1],caBuf,sizeof(caBuf));
                    iSign=1;
                    sleep(1);
                }
                else if(iSign==1)
                {
                    read(pipefd[0],caBuf,sizeof(caBuf));
                    printf("child1 says:%s\n",caBuf);
                    iSign=0;
                }
            }
        }
        else if(pid==-1)
        {
            perror("first fork");
            return -1;
        }
        return -1;
    }
    
    • 命名管道:
    • write fifo
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <stdlib.h>
    #include <unistd.h>
    #define FIFO_PATHNAME "myFifo"
    int main()
    {
        int ret=-1;
        ret=mkfifo(FIFO_PATHNAME,0777);
        if(ret==-1)
        {
            if(errno!=EEXIST)
            {
                perror("mkfifo");
                exit(EXIT_FAILURE);
            }
        }
        printf("fifo is ok\n");//管道創(chuàng)建成功
        int fd=-1;
        fd=open(FIFO_PATHNAME,O_WRONLY);//只寫打開
        if(errno!=EEXIST)
        {
            perror("mkfifo");
            exit(EXIT_FAILURE);
        }
        ret=write(fd,"hello world",11);
        if(ret>0)
        {
            printf("write %d bytes to fifo success\n",ret);
        }
        close (fd);
        //當沒有文件進行讀的時候就會阻塞在那里
        return 0;
    }
    
    • read fifo
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <stdlib.h>
    #include <unistd.h>
    #define FIFO_PATHNAME "myFifo"
    int main()
    {
        int ret=-1;
        ret=mkfifo(FIFO_PATHNAME,0777);
        if(ret==-1)
        {
            if(errno!=EEXIST)
            {
                perror("mkfifo");
                exit(EXIT_FAILURE);
            }
        }
        printf("fifo is ok\n");//管道創(chuàng)建成功
        int fd=-1;
        fd=open(FIFO_PATHNAME,O_RDONLY);//只寫打開
        if(errno!=EEXIST)
        {
            perror("mkfifo");
            exit(EXIT_FAILURE);
        }
        char caBuf[64]={'\0'};
        ret=read(fd,caBuf,sizeof(caBuf));
        if(ret>0)
        {
            printf("read %d bytes to fifo success\n",ret);
        }
        close (fd);
        printf("%s",caBuf);
        //當沒有文件進行讀的時候就會阻塞在那里
        return 0;
    }
    
Paste_Image.png
  1. 共享內(nèi)存:

    • 定義:共享內(nèi)存是被多個進程共享的一部分物理內(nèi)存。共享內(nèi)存是進程間共享數(shù)據(jù)的一種最快的方法,一個進程向共享內(nèi)存區(qū)域?qū)懭肓藬?shù)據(jù),共享這個內(nèi)存區(qū)域的所有進程就可以立刻看到其中的內(nèi)容。


      Paste_Image.png
    • int shmget(key_t key, size_t size, int shmflg);
      • 第一個參數(shù):共享內(nèi)存塊的名字
      • 第二個參數(shù):這塊共享內(nèi)存的大小
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <unistd.h>
    #include <stdlib.h>
    int main()
    {
        int shmid=-1;
        //int shmget(key_t key, size_t size, int shmflg);
        //第一個參數(shù):內(nèi)存塊名字
        //第二個參數(shù):共享內(nèi)存的大小
        shmid=shmget(0x1024,1024,IPC_CREAT|S_IRUSR|S_IWUSR);//內(nèi)存塊名字,內(nèi)存塊大小,創(chuàng)建
        if(shmid==-1)
        {
            perror("shmget");
            exit(EXIT_FAILURE);
        }
        printf("shmget ok=%d\n",shmid);
        return 0;
    }
    
    Paste_Image.png

    向內(nèi)存存儲數(shù)據(jù)

    void *pRet=NULL;
    pRet=shmat(shmid,NULL,0);//返回內(nèi)存地址
    if((void *)-1==pRet)//返回值類型就是(void*)-1
    {
        perror("shmat");
        exit(EXIT_FAILURE);
    }
    char *pData = "I want my tears back";
    memcpy(pRet,pData,strlen(pData));
    shmdt(pRet);//斬斷關聯(lián)
    
    return 0;
    
    Paste_Image.png

    讀取內(nèi)存中數(shù)據(jù)

    void *pRet=NULL;
    pRet=shmat(shmid,NULL,SHM_RDONLY);//0:讀寫,SHM_RDONLY:讀,沒有只寫
    if((void *)-1==pRet)//返回值類型就是(void*)-1
    {
        perror("shmat");
        exit(EXIT_FAILURE);
    }
    char caBuf[32]={'\0'};
    memset(caBuf,'\0',sizeof(caBuf));
    //數(shù)據(jù)讀取之后任然留在共享內(nèi)存里面
    //直到下次寫數(shù)據(jù)時被覆蓋
    memcpy(caBuf,pRet,sizeof(caBuf));
    printf("%s\n",caBuf);
    
    struct shmid_ds shmInfo;
    shmctl(shmid,IPC_STAT,&shmInfo);
    printf("shm size=%ld\n",shmInfo.shm_segsz);
    
    shmdt(pRet);//斬斷關聯(lián)
    
    Paste_Image.png

    釋放內(nèi)存空間

    shmctl(shmid,IPC_RMID,NULL);//RMID表示刪除
    //shmdt(pRet);//斬斷關聯(lián)
    
  2. 內(nèi)存映射

  • 定義:mmap是一種內(nèi)存映射文件的方法,即將一個文件或者其它對象映射到進程的地址空間,實現(xiàn)文件磁盤地址和進程虛擬地址空間中一段虛擬地址的一一對映關系。實現(xiàn)這樣的映射關系后,進程就可以采用指針的方式讀寫操作這一段內(nèi)存,而系統(tǒng)會自動回寫臟頁面到對應的文件磁盤上,即完成了對文件的操作而不必再調(diào)用read,write等系統(tǒng)調(diào)用函數(shù)。相反,內(nèi)核空間對這段區(qū)域的修改也直接反映用戶空間,從而可以實現(xiàn)不同進程間的文件共享。
Paste_Image.png
#include <sys/mman.h>
#include <stdio.h>
#include <string.h>

#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
    int fd=-1;
    fd=open("test",O_RDWR);
    if(fd==-1)
    {
        perror("open");
        exit(-1);
    }
    //映射
    void *pRet=NULL;
    pRet=mmap(NULL,32,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);//最后一個偏移量
    if((void *)-1==pRet)
    {
        perror("mmap");
        exit(-1);
    }
    //將數(shù)據(jù)格式化的保存到字符數(shù)組里去
    sprintf((char*)pRet,"%s %d %.2f","老司機開車拉",1024,3.14);//(char*)pRet用在pRet的空間用char型保存
    munmap(pRet,32);

    return 0;
}
Paste_Image.png
#include <sys/mman.h>
#include <stdio.h>
#include <string.h>

#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
    int fd=-1;
    fd=open("test",O_RDWR);
    if(fd==-1)
    {
        perror("open");
        exit(-1);
    }
    //映射
    void *pRet=NULL;
    pRet=mmap(NULL,32,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);//最后一個偏移量
    if((void *)-1==pRet)
    {
        perror("mmap");
        exit(-1);
    }
    //將數(shù)據(jù)格式化的保存到字符數(shù)組里去
    char caBuf[32]={'\0'};
    int iData=0;
    float fData=0;
    sscanf(pRet,"%s%d%f",caBuf,&iData,&fData);
    printf("%s %d %.2f\n",caBuf,iData,fData);
    munmap(pRet,32);
    close(fd);
    return 0;
}
Paste_Image.png
  1. 信號:signal
  • kill:發(fā)送一個信號到進程里去
    • kill -l


      Paste_Image.png
    • 前32個信號非可靠信號,后32個可靠信號
  • 信號的產(chǎn)生:分為硬件產(chǎn)生的信號和軟件產(chǎn)生的信號。
  • 平時用的kill -9 就是SIGKILL
/*kill()*/
#include <sys/types.h>
#include <signal.h>
/*fork()*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
    pid_t pid=-1;
    pid=fork();
    if(pid>0)
    {
        while(1)
        {
            printf("come on!kill me please!\n");
            sleep(1);
        }
    }
    else if(pid==0)
    {
        int i=5;
        while (1)
        {
            if(i==0)
            {   
                printf("time for killing\n");
                kill(getppid(),SIGKILL);//getppid()得到父進程進城號
                break;
            }
            else
            {
                printf("still have %d sec to kill that sb\n",i);
                sleep(1);
            }
            i--;
        }
    }
    else if(pid==-1)
    {
        perror("fork");
        exit(-1);
    }
}
Paste_Image.png
  • alarm信號:鬧鐘
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    //在指定的秒數(shù)給本進程發(fā)送一個SIGALRM信號
    //該信號的默認處理是結(jié)束進程
    alarm(5);
    while(1)
    {
        printf("hahahahahahahahah...\n");
        sleep(1);
    }
    return 0;
}
Paste_Image.png
  • raise
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
int main()
{
    int i=5;
    //在指定的秒數(shù)給本進程發(fā)送一個SIGALRM信號
    //該信號的默認處理是結(jié)束進程
    while(1)
    {
        if(i==0)
        {
            raise(SIGKILL);
        }
        else
        {
            printf("kill me ...\n");
        }
        i--;
        sleep(1);
    }
    return 0;
}
Paste_Image.png
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容