2014-12-04 15 views
0

我想創建一個小程序,創建兩個兒子(proccess),每個兒子生成隨機數。父親等待兒子並總結結果。
問題:爲使其正常工作,我需要做些什麼修改?
這就是我迄今爲止所做的。
共享內存 - 兒子生成數字和父親的結果[UNIX]

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/shm.h> 
#include <string.h> 
#include <stdlib.h> 
#include <time.h> 

#define SEGSIZE 100 

void main() 
{ 
    key_t key; 
    int shmid; 
    char *segptr; 
    int status=0; 
    int r_pid=1; 
    int r_pid2=1; 
    key = ftok(".", 'T'); 
    if((shmid = shmget(key, SEGSIZE,IPC_CREAT|IPC_EXCL|0666))== -1) 
    { 
     printf("Shared memory segment exists - opening as client\n"); 
     if((shmid = shmget(key, SEGSIZE, 0)) == -1) 
     { 
      perror(" bad shmget"); 
      exit(1);    
     } 

    } 
    else 
    {  
     printf("Creating new shared memory segment\n");   
    } 
    if((segptr = shmat(shmid, 0, 0)) == NULL) 
    {   
      perror("shmat");     
      exit(1);   
    } 
    r_pid=fork(); 
    if(r_pid!=0) 
      r_pid2=fork(); 

    if(r_pid<0 || r_pid2<0) 
    { 
      printf("No child created"); 
      exit(1); 
    } 
    if(r_pid==0 ) 
    { 
      printf("The child process with PID number : %d"" (his parent PID is %d) writes a text to the shared"" memory\n",getpid(),getppid()); 
      strcpy(segptr,"12"); 
    } 
    else if(r_pid2==0) 
    { 
     segptr+=2; 
     printf("The child process with PID number : %d" " (his parent PID is %d) writes a text to the shared"" memory\n",getpid(),getppid()); 
     strcat(segptr,"14"); 
    } 
    else 
    { 
     r_pid = wait(&status); 
     r_pid2 = wait(&status); 
     printf(" The following text is received by the ""parent process with PID number pid: %d pid2 : %d text: %s\n",r_pid,r_pid2,segptr); 


    } 

    shmctl(shmid, IPC_RMID, 0); 

} 

的建議是歡迎!謝謝。
編輯
下面是一些更新:
如果我初始化segptr與像無用的字符:strpy(segptr,「A」)的兒子
,然後我做的strcat(segptr,「測試1」)和r_pid2我做strcat(segptr,「test2」)
父親將打印test1test2,反之亦然。

+0

我建議你花時間來讓你的代碼格式,因此更容易:-)閱讀...如果你在你的IDE良好的格式化源(或txt文件),將其全部粘貼,然後突出顯示用鼠標粘貼的內容,然後單擊編輯框左上方的格式化工具。祝你好運。 – shellter 2014-12-04 17:12:27

+0

您現在可以查看代碼,我從docx複製了它,這就是它的原因。 – 2014-12-04 17:21:27

+0

問題是什麼? – 2014-12-04 17:31:34

回答

0

不能保證第一個孩子在第二個孩子之前運行。因此,

 segptr+=2; 
     … 
     strcat(segptr,"14"); 

可以之前

  strcpy(segptr,"12"); 

造成「14」的第一數位由「12」的空終止字符被覆蓋執行。

我需要做些什麼才能使它工作?

確保寫入不重疊, G。通過改變

  strcpy(segptr,"12"); 

 strncpy(segptr, "12", 2);