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,反之亦然。
我建議你花時間來讓你的代碼格式,因此更容易:-)閱讀...如果你在你的IDE良好的格式化源(或txt文件),將其全部粘貼,然後突出顯示用鼠標粘貼的內容,然後單擊編輯框左上方的格式化工具。祝你好運。 – shellter 2014-12-04 17:12:27
您現在可以查看代碼,我從docx複製了它,這就是它的原因。 – 2014-12-04 17:21:27
問題是什麼? – 2014-12-04 17:31:34