IPC - Linux中的共享编程程序

时间:2014-07-15 01:51:13

标签: c linux ipc shared-memory

我正在尝试创建一个程序,它可以在共享内存的帮助下,在命名,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

的错误

任何人都可以帮我这个吗?在这个程序中我有什么问题吗?

提前谢谢。

1 个答案:

答案 0 :(得分:5)

除了几个编译器警告(*shmem = "*";while(*shmem == "*"))之外 和一些编程错误......你有一个设计问题。

应使用信号量控制共享内存访问/更新 序列化对数据的访问并防止部分更新。

关于你的细分错误...... 它似乎在scanf("%s", data);的receiver.c中,因为你是 从stdin接收输入data,这只是指向char的指针... ...即没有分配输入空间。

希望,这应该让你去......