2015-09-21 18 views
0

以下是共享內存實現的程序,其中父進程和子進程將使用共享內存來打印父進程給出的下一個字母表。爲什麼父進程根本不執行?

有一個共享內存,兩個進程都附加到它以獲得所需的結果。在我的代碼中,父進程根本不執行。

#include<stdio.h> 
#include<stdlib.h> 
#include<unistd.h> 
#include<string.h> 
#include<sys/ipc.h> 
#include<sys/shm.h> 
#include<sys/types.h> 
int main(int argc,char *argv[]) 
{ 
    int smid; 
    pid_t x; 
    char *sm; 
    smid=shmget(IPC_PRIVATE,(size_t)sizeof(char),IPC_CREAT); 
    x=fork(); 
    if(x>0) 
    { 

    sm=(char *)shmat(smid,NULL,0); 
    sprintf(sm,"%s",argv[1]); 
    printf("Parent wrote:\n"); 
    puts(sm); 
    sleep(4); 
    printf("Parent got:\n"); 
    puts(sm); 
    shmdt(sm); 
    shmctl(smid,IPC_RMID,NULL); 
     } 
    else if(x==0) 
    { 
     sleep(2); 
sm=(char *)shmat(smid,NULL,0); 
printf("Child read:\n"); 
puts(sm); 
sm[0]++; 
    } 
    return 0; 
} 
+1

結論性的語句沒有幫助。你需要告訴我們你期望的輸出和你得到的輸出。或者,至少,*你如何得出父母不執行的結論。 –

+0

控件不會進入父進程的塊。 「父母寫」或「父母得到」根本沒有被輸出。而是它說「分段錯誤(核心轉儲)」 –

+0

再次,這是一個結論。什麼讓你有那個想法?你有什麼證據可以得出這個結論?你期望什麼?你觀察到了什麼? –

回答

1

差不多對這一計劃的

smid=shmget(IPC_PRIVATE,(size_t)sizeof(char),IPC_CREAT); 

SRC的原因被分配一個字節,但接踵而來的是的bizzare,

char *src=(char *)malloc(sizeof(char)); 
    strcpy(src,argv[0]); // argv[0] is more than 1 
    sm=(char *)shmat(smid,NULL,0); 
    sprintf(sm,"%s",src); // it has NULL at the end 

鬆散的固定程序..

int smid; 
    pid_t x; 
    char *sm; 
    smid=shmget(IPC_PRIVATE,(size_t)120*sizeof(char),IPC_CREAT|0666); // permissions and size are important 
    perror("smid "); 
    x=fork(); 
    if(x>0) 
    { 
      char *src=(char *)malloc(120*sizeof(char)); // size is the key here 
      sm=(char *)shmat(smid,NULL,0); 
      perror("shmat"); 
      strcpy(src,argv[0]); 
      sprintf(sm,"%s",src); 
      printf("Parent wrote:\n"); 
      puts(sm); 
      sleep(4); 
      printf("Parent got:\n"); 
      puts(sm); 
      shmdt(sm); 
      shmctl(smid,IPC_RMID,NULL); 
    } 
    else if(x==0) 
    { 
      sleep(2); 
      sm=(char *)shmat(smid,NULL,0); 
      printf("Child read:\n"); 
      puts(sm); 
      sm[0]++; 
    } 
+0

對不起,我更改了我的代碼。現在它是argv [1],我不再使用src了。我直接將argv [1]傳遞給sprintf而不是src。 –

+0

非常感謝。這解決了我的問題。 –

+0

非常感謝。這解決了我的問題。 –

2

你必須在程序未定義行爲。您爲單個字符分配內存,然後使用strcpy,這將很可能複製更多比一個字符(即使它複製一個字符,您必須記住它也複製字符串終止符,因此實際上覆制兩個字符)。

未定義的行爲往往是崩潰的主要原因,這可能是您的代碼中發生的事情。

相關問題