【发布时间】:2014-12-04 16:52:41
【问题描述】:
我正在尝试创建一个创建两个儿子( proccess )的小程序,每个儿子生成随机数。父亲等待儿子并总结结果。
问题:我需要做哪些修改才能使其正常工作?
这就是我到目前为止所做的。
#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,"test1") 和 r_pid2 我做 strcat(segptr,"test2")
父亲将打印 test1test2 或反之亦然。
【问题讨论】:
-
我建议您花时间格式化您的代码,以便于阅读 :-) ... 如果您的 IDE(或 txt 文件)中有格式良好的源代码,请将其全部粘贴中,然后用鼠标突出显示您粘贴的内容,然后单击编辑框左上方的
{}格式化工具。祝你好运。 -
你现在可以查看代码了,我是从 docx 复制的,这就是它的原因。
-
问题是什么?
标签: c unix process shared-memory