【发布时间】:2014-07-15 01:51:13
【问题描述】:
我正在尝试创建一个程序,它可以在共享内存的帮助下,在两个进程之间进行通信,命名为 processor.c 和 receiver.c,充当客户端和服务器。
第一个程序receiver.c 在一个无限循环中运行,一次一行地从用户接收字母数字字符串作为输入。从标准输入读取一行后,该程序将此信息发送给另一个程序。两个进程之间的数据共享应该通过共享内存进行。第二个程序 processor.c 创建一个输出文件 vowels.out 并等待接收程序发送用户输入。一旦从接收器接收到一行,它就会计算该行中元音的数量,并将元音计数与原始行一起转储到 vowels.out 文件中。这个程序也是无限循环运行的。
这里是程序 -
processor.c
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdio.h>
#define SHM_SIZE 10240 /* make it a 10K shared memory segment */
void main()
{
int v=0;
char ch;
int id_shm;
key_t random_key; /* Keys are used for requesting resources*/
char *shmem, *seg;
/* Segment named "6400", should be created by the server. */
random_key = 6400;
/* Locate the segment. Used - shmget() */
if ((id_shm = shmget(random_key, SHM_SIZE, 0660)) < 0) {
perror("shmget");
exit(1);
}
/* Attaching segment to the data spaces. Used - shmat() */
if ((shmem = shmat(id_shm, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
/* Creation of File */
FILE *op_file;
op_file = fopen("vowels.out", "a");
/* Now read what the server put in the memory. */
seg = shmem;
while (shmem != NULL) /* 'while' - use of entry controlled loop */
{
while ((ch=fgetc(op_file))!=EOF)
{
if (ch=='A'||ch=='a'||ch=='E'||ch=='e'||ch=='I'||ch=='i'||ch=='O'||ch=='o'||ch=='U'||ch=='u')
{
v++;
}
}
fprintf(op_file, "%s, %d \n", shmem, v);
*shmem = "*";
while(*shmem == "*")
{
sleep(6);
}
}
fclose(op_file);
}
receiver.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 10240 /* make it a 10K shared memory segment */
void main()
{
key_t random_key; /* Keys are used for requesting resources*/
int id_shm;
char *data, *shmem;
random_key = 6400;
/* Creation of the segment. Used - shmget()*/
if ((id_shm = shmget(random_key, SHM_SIZE, 0660 | IPC_CREAT)) == -1)
{
perror("shmget");
exit(1);
}
/* Addition of segment to the data spaces. Used - shmat() */
if ((shmem = shmat(id_shm, NULL, 0)) == (char *) -1)
{
perror("shmat");
exit(1);
}
while (1) /* 'while' - use of entry controlled loop to check on access */
{
scanf("%s", data);
data = shmem; /* Mapping of data */
while(*shmem != "*")
{
sleep(6);
}
}
}
但我收到指定 Segmentation Fault 的错误
谁能帮我解决这个问题?我在这个程序中做错了什么吗?
提前谢谢你。
【问题讨论】:
-
能否隔离出发生分段错误的线路?如果您使用调试信息编译它(例如,在 gcc 中使用
-g),它是否也会失败?在使用 Linux 时,您还可以尝试使用 Valgrind 来收集有关错误的更多信息。 -
我是 linux 的初学者,在 windows 8.1 机器上使用 virtual box。在编译过程中会显示警告,例如 --receiver.c:36:15: comparison between pointer and integer[enabled by default]
标签: c linux ipc shared-memory