簡體   English   中英

使用共享內存從一個進程到另一個進程發送字符串

[英]send string from process to process using shared memory

我是共享內存的新手,我嘗試使用這些代碼將一個進程中的字符串發送到另一個,當另一個進程接收該字符串時,它將共享內存中的第一個字符設置為等於'a'字符。 但是,當我想運行其中之一時,出現分段錯誤消息:

     #include <stdlib.h>
        #include<stdio.h>
        #include <string.h>
        int main(int argc , char *argv[])
        {
            key_t key = 111 ;
            int id = shmget(key , 512 , 1 | 0666);
            char *s  = shmat(id  , 0 , 0) ; 
            strcpy(s,argv[1]) ; 
            while(*s == 'a') sleep(1) ;
            return 0 ;
        }
   // and this is the code for reciever >     
        #include <stdlib.h>
        #include<stdio.h>
        int main(int argc , char *argv[])
        {
            key_t key = 111 ;
            int id = shmget(key , 512 , 1 | 0666);
            char* shm = shmat(id , 0 , 0 ) ;
            char *s = shm ; 
            for(s =  shm; *s != NULL ; s++ )
                putchar(*s) ;
            *s = 'a' ;
            return 0 ;
        }

我解決了這個問題,我包括以下庫->和,然后將shmget函數的最后一個輸入更改為IPC_CREAT | |。 0666

看起來像在for循環中,您正在遞增's'變量,因此實際上並不是將字符串的第一個字符設置為'a',而是將空終止符設置為'a'。

嘗試改變

*s = 'a';

*shm = 'a';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM